﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
using System.Linq;
using System.Windows.Forms.DataVisualization.Charting;
using MySql.Data.MySqlClient;
using AutoUpdaterDotNET;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
using ZLGCAN;
using Newtonsoft.Json;
using Peak.Can.Basic;
using TPCANHandle = System.UInt16;
using TPCANBitrateFD = System.String;
using TPCANTimestampFD = System.UInt64;
using System.Security.Cryptography;
using static WindowsApplication1.MyDefine;
using Microsoft.VisualBasic;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;
using System.Security.Policy;
using Newtonsoft.Json.Linq;
using System.Reflection;
using System.Web;
using System.Diagnostics;
using System.IO.Packaging;
using System.IO.Compression;
using System.Windows.Shell;
using System.Text.RegularExpressions;
using System.Collections;
using System.Web.Script.Serialization;
using AntdUI;
using Microsoft.VisualBasic.Logging;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;

//以下为简易定义与调用方式，在项目属性->生成->勾选使用不安全代码即可
unsafe public struct VCI_BOARD_INFO//使用不安全代码
{
    public UInt16 hw_Version;
    public UInt16 fw_Version;
    public UInt16 dr_Version;
    public UInt16 in_Version;
    public UInt16 irq_Num;
    public byte can_Num;

    public fixed byte str_Serial_Num[20];
    public fixed byte str_hw_Type[40];
    public fixed byte Reserved[8];
}

/////////////////////////////////////////////////////
//2.定义CAN信息帧的数据类型。
unsafe public struct VCI_CAN_OBJ  //使用不安全代码
{
    public uint ID;
    public uint TimeStamp;        //时间标识
    public byte TimeFlag;         //是否使用时间标识
    public byte SendType;         //发送标志。保留，未用
    public byte RemoteFlag;       //是否是远程帧
    public byte ExternFlag;       //是否是扩展帧
    public byte DataLen;          //数据长度
    public fixed byte Data[8];    //数据
    public fixed byte Reserved[3];//保留位

}
public struct CAN_ID_DATA
{
    public uint ID;
    public string strbuff;
}
//3.定义初始化CAN的数据类型
public struct VCI_INIT_CONFIG 
{
    public UInt32 AccCode;
    public UInt32 AccMask;
    public UInt32 Reserved;
    public byte Filter;   //0或1接收所有帧。2标准帧滤波，3是扩展帧滤波。
    public byte Timing0;  //波特率参数，具体配置，请查看二次开发库函数说明书。
    public byte Timing1;
    public byte Mode;     //模式，0表示正常模式，1表示只听模式,2自测模式
}

/*------------其他数据结构描述---------------------------------*/
//4.USB-CAN总线适配器板卡信息的数据类型1，该类型为VCI_FindUsbDevice函数的返回参数。
public struct VCI_BOARD_INFO1
{
    public UInt16 hw_Version;
    public UInt16 fw_Version;
    public UInt16 dr_Version;
    public UInt16 in_Version;
    public UInt16 irq_Num;
    public byte can_Num;
    public byte Reserved;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=8)] 
    public byte []str_Serial_Num;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public byte[] str_hw_Type;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public byte[] str_Usb_Serial;
}

/*------------数据结构描述完成---------------------------------*/
 public struct CIRCULARBUFF_s
{
    public UInt16 head;
    public UInt16 tail;
    public UInt32 count;
} ;

namespace WindowsApplication1
{

    public partial class main_form : AntdUI.Window //Form
    {
        DeviceInfo[] kDeviceType =
        {
            new DeviceInfo(Define.ZCAN_USBCAN1, 1),
            new DeviceInfo(Define.ZCAN_USBCAN2, 2),
            new DeviceInfo(Define.ZCAN_USBCAN_E_U, 1),
            new DeviceInfo(Define.ZCAN_USBCAN_2E_U, 2),
            new DeviceInfo(Define.ZCAN_PCIECANFD_100U, 1),
            new DeviceInfo(Define.ZCAN_PCIECANFD_200U, 2),
            new DeviceInfo(Define.ZCAN_PCIECANFD_200U_EX,2),
            new DeviceInfo(Define.ZCAN_PCIECANFD_400U, 4),
            new DeviceInfo(Define.ZCAN_USBCANFD_200U, 2),
            new DeviceInfo(Define.ZCAN_USBCANFD_100U, 1),
            new DeviceInfo(Define.ZCAN_USBCANFD_MINI, 1),
        };
        uint[] kBaudrate =
        {
            20000,//20kbps
            50000,//50kbps
            125000,//125kbps
            250000,//250kbps
            500000,//500kbps
            800000,//800kbps
            1000000,//1Mbps
        };
        private System.Windows.Forms.AGaugeLabel aGaugelabelVol;
        private System.Windows.Forms.AGaugeLabel aGaugelabelCur;
        CellLevel_s cellLevel = new CellLevel_s();
        clb_facinfo_t FactoryInfo = new clb_facinfo_t();
        const uint CRC32_FACTOR = 0x04C11DB7;
        const bool SYSSETFACINFO = false;//设置出厂信息,1:只有出厂设置界面,0:正常界面;
        //const bool BMUEOLMODE = true;//从板 EOL模式      
        const bool LogInPage = false;//是否有登录界面

        public MySqlConnection conn = null;//连接对象
        public MySqlCommand comm = null;//语句执行对象
        public MySqlDataReader dr = null;//语句执行结果数据对象
        
        MyDefine.Flag InSlaveMode = new MyDefine.Flag(); 
        byte InSlaveMode_updata = 0;
        byte InSlaveCheck_updata = 0;//校验成功 置 1
        byte Send_SlaveCheckcnt = 0;
        byte InSlaveAssignaddr_updata = 0;
        byte Send_SlaveAssignaddrcnt = 0;

        #region Clb_init
        Byte CLB_CRC_BASE = 0X3C;
        Byte CLB_DEV_PC = 0;
        Byte CLB_DEV_ECU = 1;
        Byte CLB_DEV_BMS = 3;
        Byte CLB_OPT_READ = 0;
        Byte CLB_OPT_WRITE = 1;
        Byte CLB_OPT_FACTORY = 2;
        Byte CLB_OPT_REPLY = 3;
        Byte[] Clb_Balacomm = new Byte[8];
        MyDefine.CLB_SIGNALNUM Clb_SignalValue = new MyDefine.CLB_SIGNALNUM();
        #endregion
        string TEXTBOXTIP = "显示上位机下发的can报文";

        ushort dbcCM_Line = 0;
        ushort dbcBA_DEF_Line = 0;

        string dbcFileName;
        byte[,] CanBaudArr = new byte[2, 9] { { 0x18, 0x09, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 },
            { 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x16, 0x14, 0x6F, 0x6F } };
        byte Sys_time1S_tickPage3, Sys_time200mS_tick, Sys_time1S_tickPage2;
        

        Thread recv_thread_, sendv_thread_;
        static object locker = new object();
        static object lockersend = new object();
        CIRCULARBUFF_s CircularBuff_send;
        CIRCULARBUFF_s CircularBuff_rec;
        CIRCULARBUFF_s CircularBuff_clb;

        VCI_CAN_OBJ[] RecCanData = new VCI_CAN_OBJ[2500];
        CAN_ID_DATA[] SendCanData = new CAN_ID_DATA[2500];
        UInt16[] clbData = new UInt16[100];


        MyDefine.BOOTDATA_s[] DevBootData = new MyDefine.BOOTDATA_s[9];//8个从板的升级数据,状态
        #region USBCAN-2
        /// <summary>
        /// 
        /// </summary>
        /// <param name="DeviceType"></param>
        /// <param name="DeviceInd"></param>
        /// <param name="Reserved"></param>
        /// <returns></returns>
        /*------------兼容ZLG的函数描述---------------------------------*/
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_OpenDevice(UInt32 DeviceType, UInt32 DeviceInd, UInt32 Reserved);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_CloseDevice(UInt32 DeviceType, UInt32 DeviceInd);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_InitCAN(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_INIT_CONFIG pInitConfig);

        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_ReadBoardInfo(UInt32 DeviceType, UInt32 DeviceInd, ref VCI_BOARD_INFO pInfo);

        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_GetReceiveNum(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_ClearBuffer(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);

        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_StartCAN(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_ResetCAN(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);

        [DllImport("controlcan.dll")]
        static extern Int32 VCI_Transmit(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_OBJ pSend, UInt32 Len);

        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_Receive(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_OBJ pReceive, UInt32 Len, Int32 WaitTime);

        /*------------其他函数描述---------------------------------*/

        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_ConnectDevice(UInt32 DevType, UInt32 DevIndex);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_UsbDeviceReset(UInt32 DevType, UInt32 DevIndex, UInt32 Reserved);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_FindUsbDevice2(ref VCI_BOARD_INFO pInfo);
        /*------------函数描述结束---------------------------------*/
        #endregion

        static UInt32 m_devtype;//USBCAN2
        uint SENDBUFFSIZE = 2000;
        uint RECBUFFSIZE = 2000;
        int GridViewRowsCnt,lastgridview;
        UInt32 m_bOpen = 0;//can连接成功标志位
        UInt32 m_devind = 0;
        UInt32 m_canind = 0;
        byte candevtype = 0;//can设备类型 0:usbcan2 ;1:pcan;
        
        byte DBCstartFlag = 0;
        byte canMessage_stop = 1;
        byte MouseLocation;
        uint userLicensecnt = 0;
        byte NowTabConSelectedIndex = 0, NowRemoteSelectedIndex = 0, NowExternSelectedIndex = 0;
        byte CanModeSelectedIndex;
        byte SetSOCValue = 100;//目标soc值,使实际soc值渐变
        byte SetSOHValue = 100;
        byte SetSOEValue = 100;

        UInt16 ErrorLogCnt;
        UInt16 BMS_CellVoltTempPage = 1;//页面编号
        UInt16 BMS_PAGECELLNUMBER_Max = 64;//pack最大电芯数量
        UInt16 BMS_BMUCellNum = 52;//pack电芯数量
        UInt16 BMS_AfeCellNum = 13;
        UInt16 BMS_AFECELLMax = 16;
        bool syshasfalutmessage = false;//出现故障
        System.Windows.Forms.Label[] PCBTemplabel = new System.Windows.Forms.Label[32];
        UseErrorInfo[] Falutinfo_gb = new UseErrorInfo[80];
        UseErrorInfo[] Falutinfo = new UseErrorInfo[128];
        UseCellInfo[] CellInfo = new UseCellInfo[64];
        AntdUI.Input[] AfeVoltTbox = new AntdUI.Input[32];
        System.Windows.Forms.Label lb_cellpageMax = new System.Windows.Forms.Label();
        System.Windows.Forms.Label lb_cellpageMin = new System.Windows.Forms.Label();
        System.Windows.Forms.Button[] bt_PackNum = new System.Windows.Forms.Button[8];
       
       
        /*
        *  DBC协议中用到的 
        */
        byte[] BMS_FaultInfomation_LAST = new byte[16];//存16个1字节的错误信息 上一次的
        byte[] BMS_FaultInfomation = new byte[16];//存16个1字节的错误信息

        byte[] BMS_GB_FaultInfomation = new byte[10];//国标警告信号
        byte[] BMS_GB_FaultInfomation_LAST = new byte[10];//国标警告信号  上一次的

        byte[] BMS_CSC_PCB_Temp = new byte[70];//从板1-64板温
        byte[] BMS_FAN_States = new byte[32];//第x个风扇开启状态
        byte[] DV_BMS_Cell_BALA_FB = new byte[512];//第x个单体的均衡状态
        byte[] DV_EOL_BALA_COMM = new byte[512];//第x个单体的均衡指令
        UInt16[] BMS_CellVolt = new UInt16[512];//第X节单体电压
        UInt16[] BMS_ClusterTemp = new UInt16[512];//第X节单体温度
        UInt16[] BMS_AFEVolt = new UInt16[32];//AFE电压
        UInt16[] BMS_AFETemp = new UInt16[65];//AFE内部温度
        MyDefine.DBC_BZ_s DBCData = new MyDefine.DBC_BZ_s();
        //ID过滤
        Int32 CanIDfiltrationMIN = 0;
        Int32 CanIDfiltrationMAX = 0X800;

        string FactoryJSONFilePath;
        string FaultClbJSONFilePath;

        IList<FaultJsonResult_class> FaultJsonResults = new List<FaultJsonResult_class>();
        IList<FactoryJsonResult_class> FactoryJsonResults = new List<FactoryJsonResult_class>();

        AntList<bmsNVMfaultlogItem> antList;
        public IList<FaultJsonResult_class> GetErrJsonResults()
        {
            return FaultJsonResults;
        }
        public void SetErrJsonResults(IList<FaultJsonResult_class> temp)
        {
            FaultJsonResults = temp ;
        }
        public main_form()
        {
            InitializeComponent();

            InitializeBasicComponents();            
        }
       
        /// <summary>
        /// 窗体加载慢
        /// </summary>

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000; // 用双缓冲绘制窗口的所有子控件
                return cp;
            }
        }

        private void InitializeBasicComponents()
        {
            m_NonPnPHandles = new TPCANHandle[]
            {
                PCANBasic.PCAN_ISABUS1,
                PCANBasic.PCAN_ISABUS2,
                PCANBasic.PCAN_ISABUS3,
                PCANBasic.PCAN_ISABUS4,
                PCANBasic.PCAN_ISABUS5,
                PCANBasic.PCAN_ISABUS6,
                PCANBasic.PCAN_ISABUS7,
                PCANBasic.PCAN_ISABUS8,
                PCANBasic.PCAN_DNGBUS1
            };

            aGaugelabelVol = aGaugeVol.GaugeLabels.FindByName("GaugeLabel2");//簇电压仪表盘内对应的电压值
            aGaugelabelCur = aGaugeCur.GaugeLabels.FindByName("GaugeLabel2");//簇电流仪表盘内对应的电流值
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            
            this.Width = 950; 
            this.Height = 550;
            this.BackgroundImage = Properties.Resources.rjmain;
            
            //登录界面
            user_password.Text = "admin";
            user_name.Text = "admin";
            if (LogInPage)
            {
                LogIn();
            }          
            //设备界面
            UploadCanDev();//获取CAN设备列表
            label15.Text = "";
            comboBox_Mode.SelectedIndex = 0;
            CanModeSelectedIndex = (byte)comboBox_Mode.SelectedIndex;
            comboBox_DevIndex.SelectedIndex = 0;
            comboBox_canbaud.SelectedIndex = 3;
            comboBox_pcbType.SelectedIndex = 0;
            comboBox_Remote.SelectedIndex = 0;
            comboBox_Extern.SelectedIndex = 0;
            textBox_ID.Text = "0";
            textBox_Data1.Text = "00 00 00 00 00 00 00 00";
            button_Send1.Enabled = false;
            dataGridViewcan.Rows.Add(500);

            //选择是否未出厂设置界面
            if (SYSSETFACINFO == true)
            {
                CanIDfiltrationMIN = 0X7F0;
                panel74.Visible = false;
                tp2.Visible = false;
                tp3.Visible = false;
                tp4.Visible = false;
                tp5.Visible = false;
                tp6.Visible = false;
                tp8.Visible = false;
                tp9.Visible = false;
                tp10.Visible = false;
                FactoryJSONFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "FactoryFormula.json";
                button27.BackgroundImage = Properties.Resources.REFRESH;
                UpLoadFactoryFormulaCjsonFile(FactoryJSONFilePath);
                
                return;
            }
            else
            {
                tp7.Visible = false;
            }
            //监控界面
            
            foreach (Control tbox in flowPanel.Controls)
            {
                string st = tbox.Name.ToString();
                if (st.Contains("boxafevolt"))
                {
                    string[] sArray = st.Split('t');
                    AfeVoltTbox[Convert.ToByte(sArray[1]) - 1] = (AntdUI.Input)tbox;
                }
            }
            
            //电芯信息界面
            //groupBox2.Font = new Fone(groupBox2.Font.FontFamily, 14.5, groupBox2.Font.Style);
            groupBox2.Text = "PACK " + BMS_CellVoltTempPage.ToString() + " 单体电芯信息";
            cellLevelinfoinit();
            for (byte packnum = 0; packnum < 8; packnum++)
            {
                System.Windows.Forms.Button bt_packnum = new System.Windows.Forms.Button();
                bt_packnum.BackColor = Color.White;
                bt_packnum.Image = Properties.Resources.储能柜black;
                bt_packnum.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
                bt_packnum.Size = new Size(80, 80);
                bt_packnum.Margin = new System.Windows.Forms.Padding(1);
                bt_packnum.Font = new Font("微软雅黑", 12F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
                bt_packnum.Text = "PACK "+ (packnum+1).ToString();
                bt_packnum.TextAlign = ContentAlignment.BottomCenter;
                if (packnum == 0) bt_packnum.Click += new System.EventHandler(this.btPack1_Click);
                if (packnum == 1) bt_packnum.Click += new System.EventHandler(this.btPack2_Click);
                if (packnum == 2) bt_packnum.Click += new System.EventHandler(this.btPack3_Click);
                if (packnum == 3) bt_packnum.Click += new System.EventHandler(this.btPack4_Click);
                if (packnum == 4) bt_packnum.Click += new System.EventHandler(this.btPack5_Click);
                if (packnum == 5) bt_packnum.Click += new System.EventHandler(this.btPack6_Click);
                if (packnum == 6) bt_packnum.Click += new System.EventHandler(this.btPack7_Click);
                if (packnum == 7) bt_packnum.Click += new System.EventHandler(this.btPack8_Click);
                bt_PackNum[packnum] = bt_packnum;
                this.flowLayoutPanel7.Controls.Add(bt_packnum);
            }
            bt_PackNum[0].Image = Properties.Resources.储能柜green;
            for (byte CellInfo_i = 0; CellInfo_i < BMS_PAGECELLNUMBER_Max; CellInfo_i++)
            {
                UseCellInfo useCellInfo = new UseCellInfo();
                useCellInfo.CellBALAEnable = false;
                useCellInfo.cellnumtext = (CellInfo_i + 1).ToString();
                useCellInfo.cellstatetext = "均衡未开";
                useCellInfo.celltemptext = "25.1";
                useCellInfo.cellvoltext = "2.312";
                useCellInfo.VolIcon = Properties.Resources.Battery4_30;
                useCellInfo.TempIcon = Properties.Resources.T4_30;
                useCellInfo.Size = new Size(132, 39);
                useCellInfo.Margin = new Padding(0);
                //均衡控制
                #region ADDcellbalacom_btclick
                if (CellInfo_i == 0) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch1_Click);
                if (CellInfo_i == 1) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch2_Click);
                if (CellInfo_i == 2) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch3_Click);
                if (CellInfo_i == 3) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch4_Click);
                if (CellInfo_i == 4) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch5_Click);
                if (CellInfo_i == 5) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch6_Click);
                if (CellInfo_i == 6) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch7_Click);
                if (CellInfo_i == 7) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch8_Click);
                if (CellInfo_i == 8) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch9_Click);
                if (CellInfo_i == 9) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch10_Click);
                if (CellInfo_i == 10) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch11_Click);
                if (CellInfo_i == 11) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch12_Click);
                if (CellInfo_i == 12) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch13_Click);
                if (CellInfo_i == 13) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch14_Click);
                if (CellInfo_i == 14) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch15_Click);
                if (CellInfo_i == 15) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch16_Click);
                if (CellInfo_i == 16) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch17_Click);
                if (CellInfo_i == 17) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch18_Click);
                if (CellInfo_i == 18) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch19_Click);
                if (CellInfo_i == 19) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch20_Click);
                if (CellInfo_i == 20) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch21_Click);
                if (CellInfo_i == 21) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch22_Click);
                if (CellInfo_i == 22) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch23_Click);
                if (CellInfo_i == 23) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch24_Click);
                if (CellInfo_i == 24) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch25_Click);
                if (CellInfo_i == 25) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch26_Click);
                if (CellInfo_i == 26) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch27_Click);
                if (CellInfo_i == 27) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch28_Click);
                if (CellInfo_i == 28) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch29_Click);
                if (CellInfo_i == 29) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch30_Click);
                if (CellInfo_i == 30) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch31_Click);
                if (CellInfo_i == 31) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch32_Click);
                if (CellInfo_i == 32) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch33_Click);
                if (CellInfo_i == 33) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch34_Click);
                if (CellInfo_i == 34) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch35_Click);
                if (CellInfo_i == 35) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch36_Click);
                if (CellInfo_i == 36) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch37_Click);
                if (CellInfo_i == 37) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch38_Click);
                if (CellInfo_i == 38) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch39_Click);
                if (CellInfo_i == 39) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch40_Click);
                if (CellInfo_i == 40) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch41_Click);
                if (CellInfo_i == 41) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch42_Click);
                if (CellInfo_i == 42) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch43_Click);
                if (CellInfo_i == 43) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch44_Click);
                if (CellInfo_i == 44) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch45_Click);
                if (CellInfo_i == 45) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch46_Click);
                if (CellInfo_i == 46) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch47_Click);
                if (CellInfo_i == 47) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch48_Click);
                if (CellInfo_i == 48) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch49_Click);
                if (CellInfo_i == 49) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch50_Click);
                if (CellInfo_i == 50) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch51_Click);
                if (CellInfo_i == 51) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch52_Click);
                if (CellInfo_i == 52) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch53_Click);
                if (CellInfo_i == 53) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch54_Click);
                if (CellInfo_i == 54) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch55_Click);
                if (CellInfo_i == 55) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch56_Click);
                if (CellInfo_i == 56) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch57_Click);
                if (CellInfo_i == 57) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch58_Click);
                if (CellInfo_i == 58) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch59_Click);
                if (CellInfo_i == 59) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch60_Click);
                if (CellInfo_i == 60) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch61_Click);
                if (CellInfo_i == 61) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch62_Click);
                if (CellInfo_i == 62) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch63_Click);
                if (CellInfo_i == 63) useCellInfo.bBALAClick += new System.EventHandler(bBALAswitch64_Click);
                #endregion
                this.flowLayoutPanel1.Controls.Add(useCellInfo);
                CellInfo[CellInfo_i] = useCellInfo;
            }
            
            setCellVoltInit();
            //故障信息界面
            Int16 addfinfo_gb = 0, addfinfo_i = 0; 
            MyDefine Myd = new MyDefine();
            foreach (string st in Myd.faultInfostr)
            {
                Falutinfo_gb[addfinfo_gb++] = addfaultinfo(st);
            }
            foreach (string st in Myd.faultInfostr0x1a0)
            {
                Falutinfo[addfinfo_i++] = addfaultinfo(st);
            }
            //标定界面
            FaultClbJSONFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "FaultClbItem.json";
            button24.BackgroundImage = Properties.Resources.REFRESH;
            UpLoadFaultClbrCjsonFile(FaultClbJSONFilePath, 0);

            //控制界面
            GetTreeView_ControlFun();

            //固件升级界面

            
            //帮助更新界面
            textBox42.Text = System.DateTime.Now.ToString("G");
            ReadRTCday = DateTime.Now.ToString("d");
            ReadRTCtime = DateTime.Now.ToString("T");
            textBox43.Text = DateTime.Now.ToString("T");

            //详细信息界面
            adddatatochart();
            foreach (Control Panel in flowLayoutPanel2.Controls)
            {
                foreach (System.Windows.Forms.Label label in Panel.Controls)
                {
                    string st = label.Name.ToString();
                    if (st.Contains("PCBTempiconK"))
                    {
                        string[] sArray = st.Split('K');
                        int temp = Convert.ToByte(sArray[1]) - 1;
                        if (temp < 32)
                            PCBTemplabel[temp] = label;
                    }
                }
            }
            //日志查询界面            
            InitTableColumns();
            InitData();
            table_NvmFaultlog.CellButtonClick += table_CellButtonClick;
            tabControl11.SelectedIndex = 0;
        }
        private void InitTableColumns()
        {
            table_NvmFaultlog.Columns = new ColumnCollection() {
                new Column("Numb", "序号",ColumnAlign.Center){//表格里的内容居中
                    Width = "50",
                    ColAlign = ColumnAlign.Center,//表头居中
                },
                new Column("Time", "时间戳"){
                    Width = "110",
                },
                new Column("SOC", "SOC",ColumnAlign.Center)
                {
                    Width = "50",
                    ColAlign = ColumnAlign.Center,
                },
                new Column("SOH", "SOH",ColumnAlign.Center)
                {
                    Width = "50",
                    ColAlign = ColumnAlign.Center,
                },
                new Column("BattVolt", "簇电压(V)",ColumnAlign.Center){
                    Width = "80",
                    ColAlign = ColumnAlign.Center,
                },
                 new Column("BattCur", "簇电流(A)",ColumnAlign.Center){
                    Width = "80",
                    ColAlign = ColumnAlign.Center,
                },
                new Column("CellVoltMax", "电芯最大电压(mV)",ColumnAlign.Center){
                    Width = "150",
                    ColAlign = ColumnAlign.Center,
                },
                new Column("CellVoltMaxNum", "最大电压位",ColumnAlign.Center){
                    Width = "80",
                    ColAlign = ColumnAlign.Center,
                },
                new Column("CellVoltMin", "电芯最小电压(mV)",ColumnAlign.Center){
                    Width = "150",
                    ColAlign = ColumnAlign.Center,
                },
                new Column("CellVoltMinNum", "最小电压位",ColumnAlign.Center){
                    Width = "80",
                    ColAlign = ColumnAlign.Center,
                },
                new Column("FaultInfo1", "故障信息1",ColumnAlign.Center){
                    Width = "200",
                    ColAlign = ColumnAlign.Center,
                },
                new Column("FaultInfo2", "故障信息2",ColumnAlign.Center){
                    Width = "200",
                    ColAlign = ColumnAlign.Center,
                },
                  new Column("Tip", "预留",ColumnAlign.Center){
                    Width = "50",
                    ColAlign = ColumnAlign.Center,
                },
                new Column("OptButton", "操作",ColumnAlign.Center)
                {
                    Width = "180",
                },
                new Column("CellProgress", "导出进度",ColumnAlign.Center)
                {
                    Width = "150",
                    Fixed = true,//冻结列
                },
            };
        }
        private void InitData()
        {
            antList = new AntList<bmsNVMfaultlogItem>(10);
            for (int i = 0; i < 6; i++)
            {
                antList.Add(new bmsNVMfaultlogItem
                {
                    Numb = 101 + i,
                    Time = 1734314461 + i * 7,
                    SOC = 98,
                    SOH = 99,
                    BattVolt = 1500,
                    BattCur = 23,
                    CellVoltMax = 3400,
                    CellVoltMaxNum = 32,
                    CellVoltMin = 3300,
                    CellVoltMinNum = 500,
                    FaultInfo1 = "0x0100070000000000",
                    FaultInfo2 = "0x0100070300050000",
                    Tip = "-",
                    OptButton = new CellButton[] {
                    new CellButton(Guid.NewGuid().ToString(),"详情",TTypeMini.Success),
                    new CellButton(Guid.NewGuid().ToString(),"清除",TTypeMini.Error),
                    new CellButton(Guid.NewGuid().ToString(),"导出",TTypeMini.Info)},
                    CellProgress = new CellProgress(0.5f)
                });

            }
            antList[0].OptButton[1].Enabled = false;
            antList[1].OptButton[1].Enabled = false;
            antList[2].OptButton[1].Enabled = false;
            antList[3].OptButton[1].Enabled = false;
            antList[4].CellProgress = new CellProgress(0);
            antList[5].CellProgress = new CellProgress(0);
            table_NvmFaultlog.Binding<bmsNVMfaultlogItem>(antList);
        }
        /// <summary>
        /// 操作中的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void table_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            var buttontext = e.Btn.Text;

            if (e.Record is bmsNVMfaultlogItem faultthres)
            {
                switch (buttontext)
                {
                    case "清除":
                        antList.Remove(faultthres);
                        break;
                    case "导出":

                        break;
                    case "详情":

                        break;
                }
            }
        }
        public UseErrorInfo addfaultinfo(string st)
        {
            UseErrorInfo useErrorInfo1 = new UseErrorInfo();

            if (st.Contains(" "))
            {
                string[] sArray = st.Split(' ');
                useErrorInfo1.LevelName = sArray[0];
                useErrorInfo1.InfoName = sArray[1];
            }
            else
            {
                useErrorInfo1.LevelName = "Level";
                useErrorInfo1.InfoName = st;
                
            }
            if (st.Contains("电压") )
            {
                this.flowLayoutPanel3.Controls.Add(useErrorInfo1);
                useErrorInfo1.Type = 1;
            }
            else if (st.Contains("温"))
            {
                this.flowLayoutPanel6.Controls.Add(useErrorInfo1);
                useErrorInfo1.Type = 2;
            }
            else
            {
                if (st.Contains(" "))
                {
                    useErrorInfo1.Type = 3;
                }
                else
                {  
                    useErrorInfo1.Type = 0;
                }
                this.flowLayoutPanel4.Controls.Add(useErrorInfo1);
            }
            useErrorInfo1.Size = new Size(150, 56);
            useErrorInfo1.Margin = new Padding(2);
            useErrorInfo1.ForeColor = Color.Black;
             
            return useErrorInfo1;
        }
        public void FaultClbJSONFilePathStr(string FilePath)
        {
            FaultClbJSONFilePath = FilePath;
        }
        public string FaultClbJSONFilePathStr( )
        {
            return FaultClbJSONFilePath;
        }
        void setCellVoltInit()
        {
            for (int i = 0; i < BMS_CellVolt.Length; i++)
            {
                BMS_CellVolt[i] = 3000;
            }
        }
        /// <summary>
        /// 设置电压温度范围阈值
        /// </summary>
        void cellLevelinfoinit()
        {
            cellLevel.VOL_LV1min = 0;
            cellLevel.VOL_LV1max = 2499;
            cellLevel.VOL_LV2min = 2500;
            cellLevel.VOL_LV2max = 2799;
            cellLevel.VOL_LV3min = 2800;
            cellLevel.VOL_LV3max = 3649;
            cellLevel.VOL_LV4min = 3650;
            cellLevel.VOL_LV4max = 5000;
            cellLevel.TEMP_LV1min = 0;
            cellLevel.TEMP_LV1max = 19; 
            cellLevel.TEMP_LV2min = 20;
            cellLevel.TEMP_LV2max = 94;
            cellLevel.TEMP_LV3min = 95;
            cellLevel.TEMP_LV3max = 120;
            cellLevel.TEMP_LV4min = 121;
            cellLevel.TEMP_LV4max = 165;    
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (candevtype == 0)
            {
                VCI_ClearBuffer(m_devtype, m_devind, 0);
                VCI_ClearBuffer(m_devtype, m_devind, 1);
                VCI_CloseDevice(m_devtype, m_devind);
            }
            if (candevtype == 1)
            {
                PCANBasic.Uninitialize(m_PcanHandle);
            }
            if (candevtype == 2)
            {
                Method.ZCAN_CloseDevice(device_handle_);
            }
        }
        private void EnableCtrl(bool opened)
        {
            comboBox_devtype.Enabled = !opened;
            comboBox_DevIndex.Enabled = !opened;
        }
        int channel_index_ = 0;
        IntPtr device_handle_;
        IntPtr channel_handle_;
        IntPtr errintPtr;


        //设置波特率
        private bool setBaudrate(UInt32 baud)
        {
            string path = channel_index_ + "/baud_rate";
            string value = baud.ToString();
            uint rec = Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value));
            //char* pathCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(path).ToPointer();
            //char* valueCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(value).ToPointer();
            return 1 == rec;
        }

        private bool setFdBaudrate(UInt32 abaud, UInt32 dbaud)
        {
            string path = channel_index_ + "/canfd_abit_baud_rate";
            string value = abaud.ToString();
            if (1 != Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value)))
            {
                return false;
            }
            /*
            path = channel_index_ + "/canfd_dbit_baud_rate";
            value = dbaud.ToString();
            if (1 != Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value)))
            {
                return false;
            }
            */
            return true;
        }
        //设置CANFD标准
        private bool setCANFDStandard(int canfd_standard)
        {
            string path = channel_index_ + "/canfd_standard";
            string value = canfd_standard.ToString();
            //char* pathCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(path).ToPointer();
            //char* valueCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(value).ToPointer();
            return 1 == Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value));
        }

        //设置终端电阻使能
        private bool setResistanceEnable()
        {
            string path = channel_index_ + "/initenal_resistance";
            string value = "1";
            //char* pathCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(path).ToPointer();
            //char* valueCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(value).ToPointer();
            return 1 == Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value));
        }

        //设置滤波
        private bool setFilter()
        {
            string path = channel_index_ + "/filter_clear";//清除滤波
            string value = "0";
            //char* pathCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(path).ToPointer();
            //char* valueCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(value).ToPointer();
            if (0 == Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value)))
            {
                return false;
            }
            /*
            path = channel_index_ + "/filter_mode";
            value = "2";
            //char* pathCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(path).ToPointer();
            //char* valueCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(value).ToPointer();
            if (value == "2")
            {
                return true;
            }
            
            if (0 == Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value)))
            {
                return false;
            }

            path = channel_index_ + "/filter_start";
            value = CanIDfiltrationMIN.ToString();
            //char* pathCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(path).ToPointer();
            //char* valueCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(value).ToPointer();
            if (0 == Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value)))
            {
                return false;
            }

            path = channel_index_ + "/filter_end";
            value = CanIDfiltrationMAX.ToString();
            //char* pathCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(path).ToPointer();
            //char* valueCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(value).ToPointer();
            if (0 == Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value)))
            {
                return false;
            }

            path = channel_index_ + "/filter_ack";//滤波生效
            value = "0";
            //char* pathCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(path).ToPointer();
            //char* valueCh = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(value).ToPointer();
            if (0 == Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value)))
            {
                return false;
            }
            */
            //如果要设置多条滤波，在清除滤波和滤波生效之间设置多条滤波即可
            return true;
        }
        public uint MakeCanId(uint id, int eff, int rtr, int err)//1:extend frame 0:standard frame
        {
            uint ueff = (uint)(!!(Convert.ToBoolean(eff)) ? 1 : 0);
            uint urtr = (uint)(!!(Convert.ToBoolean(rtr)) ? 1 : 0);
            uint uerr = (uint)(!!(Convert.ToBoolean(err)) ? 1 : 0);
            return id | ueff << 31 | urtr << 30 | uerr << 29;
        }
        private int SplitData(string data, ref byte[] transData, int maxLen)
        {
            string[] dataArray = data.Split(' ');
            for (int i = 0; (i < maxLen) && (i < dataArray.Length); i++)
            {
                transData[i] = Convert.ToByte(dataArray[i].Substring(0, 2), 16);
            }

            return dataArray.Length;
        }
        byte zlg_OpenCan()
        {
            device_handle_ = Method.ZCAN_OpenDevice(kDeviceType[m_devtype].device_type, m_devind, 0);
            if (0 == (int)device_handle_)
            {
                LogWork.Text = "提示:打开设备失败,请检查设备类型和设备索引号是否正确";
                return 0;
            }
            return 1;
        }
        
        byte zlg_CanInit(byte CanOpen)
        {
            if (0 == CanOpen)
            {
                LogWork.Text = "提示:设备还没打开";
                return 0;
            }
            uint type = kDeviceType[comboBox_devtype.SelectedIndex].device_type;
            bool pcieCanfd = type == Define.ZCAN_PCIECANFD_100U ||
                type == Define.ZCAN_PCIECANFD_200U ||
                type == Define.ZCAN_PCIECANFD_400U ||
                type == Define.ZCAN_PCIECANFD_200U_EX;
            bool usbCanfd = type == Define.ZCAN_USBCANFD_100U ||
                type == Define.ZCAN_USBCANFD_200U ||
                type == Define.ZCAN_USBCANFD_MINI;
            bool canfdDevice = usbCanfd || pcieCanfd;

            if (usbCanfd)
            {
                if (!setCANFDStandard(0)) //设置CANFD标准
                {
                    LogWork.Text = "提示:设置CANFD标准失败";
                    return 0;
                }
            }            
            
            if (!canfdDevice)
            {
                if (!setBaudrate(kBaudrate[comboBox_canbaud.SelectedIndex]))
                {
                    LogWork.Text = "提示:设置波特率失败";
                    return 0;
                }
            }
            else
            {
                bool result = true;
                if (usbCanfd)
                {
                    if (type == Define.ZCAN_USBCANFD_200U)
                    {
                        string path = "0/set_device_recv_merge";
                        string value = "0";
                        Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value));
                    }
                    result = setFdBaudrate(kBaudrate[comboBox_canbaud.SelectedIndex], kBaudrate[comboBox_canbaud.SelectedIndex]);
                }
                else if (pcieCanfd)
                {
                    result = setFdBaudrate(kBaudrate[comboBox_canbaud.SelectedIndex], kBaudrate[comboBox_canbaud.SelectedIndex]);
                    if (type == Define.ZCAN_PCIECANFD_400U || type == Define.ZCAN_PCIECANFD_200U_EX)
                    {
                        string path = "0/set_device_recv_merge";
                        string value = "0";
                        Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value));
                    }
                }
                if (!result)
                {
                    LogWork.Text = "提示:设置波特率失败";
                    return 0;
                }
            }
            
            ZCAN_CHANNEL_INIT_CONFIG config_ = new ZCAN_CHANNEL_INIT_CONFIG();
            
            config_.canfd.mode = (byte)comboBox_Mode.SelectedIndex;
            if (usbCanfd)
            {
                config_.can_type = Define.TYPE_CANFD;
            }
            else if (pcieCanfd)
            {
                config_.can_type = Define.TYPE_CANFD;
                config_.can.filter = 0;
                config_.can.acc_code = 0;
                config_.can.acc_mask = 0xFFFFFFFF;
                config_.can.mode = 0;
            }
            else
            {
                config_.can_type = Define.TYPE_CAN;
                config_.can.filter = 0;
                config_.can.acc_code = 0;
                config_.can.acc_mask = 0xFFFFFFFF;
                config_.can.mode = 0;
            }
            
            IntPtr pConfig = Marshal.AllocHGlobal(Marshal.SizeOf(config_));
            Marshal.StructureToPtr(config_, pConfig, true);

            //int size = sizeof(ZCAN_CHANNEL_INIT_CONFIG);
            //IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(size);
            //System.Runtime.InteropServices.Marshal.StructureToPtr(config_, ptr, true);
            channel_handle_ = Method.ZCAN_InitCAN(device_handle_, (uint)channel_index_, pConfig);
            Marshal.FreeHGlobal(pConfig);

            //Marshal.FreeHGlobal(ptr);

            if (0 == (int)channel_handle_)
            {
                LogWork.Text = "提示:初始化CAN失败";
                return 0;
            }
            if (!setResistanceEnable())
            {
                LogWork.Text = "提示:使能终端电阻失败";
                return 0;
            }
            /* 结合本项目具体情况,不需要设置滤波
            if (usbCanfd && !setFilter())
            {
                LogWork.Text = "提示:设置滤波失败";
                return 0;
            }
            if (type == Define.ZCAN_USBCAN_2E_U || type == Define.ZCAN_USBCAN_E_U)
            {
                if (!setFilter())
                {
                    LogWork.Text = "提示:设置滤波失败";
                    return 0;
                }
            }
            */
            return 1;
        }
        byte zlg_CanStart(byte en)
        {
            if(en == 0)
                return 0;
            if (Method.ZCAN_StartCAN(channel_handle_) != Define.STATUS_OK)
            {
                LogWork.Text = "提示:启动CAN失败";
                return  0;
            }
            return 1;
        }
        unsafe uint zlg_CanSend(VCI_CAN_OBJ pSend)
        {
            uint result = 0;//
            ZCAN_Transmit_Data can_data = new ZCAN_Transmit_Data();
            can_data.frame.data = new byte[8];
            can_data.frame.can_id = pSend.ID;
            for (int i = 0; i < pSend.DataLen; i++)
            {
                can_data.frame.data[i] = pSend.Data[i];
            }
            can_data.frame.can_dlc = pSend.DataLen; 
            can_data.transmit_type = 0;
            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(can_data));
            Marshal.StructureToPtr(can_data, ptr, true);
            result = Method.ZCAN_Transmit(channel_handle_, ptr, 1);
            Marshal.FreeHGlobal(ptr);
            if (result != 1)
                return 0;
            else
                return 1;
        }
        void CanDevConnection()
        {
            LogWork.ForeColor = Color.Black;
            //以下两行为多can卡同机测试代码，用来获取序列号与对应的设备索引号，单can卡可以不使用。
            //VCI_BOARD_INFO[] vbi2 = new VCI_BOARD_INFO[50];
            //uint num1 = VCI_FindUsbDevice2(ref vbi2[0]);
            LogWork.Text = "连接设备";
            CanModeSelectedIndex = (byte)comboBox_Mode.SelectedIndex;
            clear_fifo();
            if (m_bOpen == 1)
            {
                if (candevtype == 0)
                {
                    VCI_ClearBuffer(m_devtype, m_devind, 0);
                    VCI_ClearBuffer(m_devtype, m_devind, 1);
                    VCI_CloseDevice(m_devtype, m_devind);
                }
                if (candevtype == 1)
                {
                    PCANBasic.Uninitialize(m_PcanHandle);
                }
                if (candevtype == 2)
                {
                    Method.ZCAN_CloseDevice(device_handle_); 
                }
                m_bOpen = 0;
                StateLog.Text = "设备未连接";
                StateLog.BackColor = Color.Gainsboro;
                LogWork.Text = "断开连接";
                button_Send1.Enabled = false;
                button2.Enabled = true;
                comboBox_devtype.Enabled = true;
                comboBox_DevIndex.Enabled = true;
                comboBox_canbaud.Enabled = true;
                comboBox_pcbType.Enabled = true;
            }
            else
            {
                if (candevtype == 2)//周立功CAN盒
                {
                    byte CanOpenFlag = zlg_OpenCan();
                    byte CanInitFlag = zlg_CanInit(CanOpenFlag);
                    m_bOpen = zlg_CanStart(CanInitFlag);
                }
                if (candevtype == 1)//pcan
                {
                    m_bOpen = PCAN_Connect();
                }
                if (candevtype == 0)//创芯科技CAN盒
                {
                    if (VCI_OpenDevice(m_devtype, m_devind, 0) == 0)
                    {
                        LogWork.Text = "连接失败,检查设备类型和设备索引号";
                        return;
                    }
                    m_bOpen = 1;
                    VCI_INIT_CONFIG config = new VCI_INIT_CONFIG();
                    config.AccCode = 0;
                    config.AccMask = 4294967295;//OXFFFFFFFF
                    config.Timing0 = CanBaudArr[0, comboBox_canbaud.SelectedIndex];
                    config.Timing1 = CanBaudArr[1, comboBox_canbaud.SelectedIndex];
                    config.Filter = 1;
                    config.Mode = (byte)comboBox_Mode.SelectedIndex; ;//0 正常 ;1 只听 ;2 自测
                    /*目前是2通道,各个通道都需要单独配置一次,否则无法正常使用*/
                    VCI_InitCAN(m_devtype, m_devind, 0, ref config);
                    VCI_InitCAN(m_devtype, m_devind, 1, ref config);
                    VCI_StartCAN(m_devtype, m_devind, 0);
                    VCI_StartCAN(m_devtype, m_devind, 1);
                    VCI_ClearBuffer(m_devtype, m_devind, 0);
                    VCI_ClearBuffer(m_devtype, m_devind, 1);
                }
                if (m_bOpen == 1)
                {
                    FacInfoCheckCnt = 0;
                    comboBox_pcbType.Enabled = false;
                    StateLog.Text = "设备已连接";
                    StateLog.BackColor = Color.LimeGreen;
                    LogWork.Text = "连接成功";
                    button_Send1.Enabled = true;
                    button2.Enabled = false;
                    comboBox_devtype.Enabled = false;
                    comboBox_DevIndex.Enabled = false;
                    comboBox_canbaud.Enabled = false;
                    if (comboBox_pcbType.SelectedIndex == 0)
                    {
                        tabControl11.SelectedIndex = 1;
                    }
                    if (comboBox_pcbType.SelectedIndex == 1)//从板模式下连接成功,清空一些状态
                    {
                        InSlaveModeStateInit();
                    }
                }
            }
            setStartRec(m_bOpen);
            setStartSend(m_bOpen);
            buttonConnect.Text = m_bOpen == 1 ? "断开" : "连接";
        }
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            CanDevConnection();//m_bOpen
        }
        unsafe void zlg_CanRec()
        {
            ZCAN_Receive_Data[] RecData = new ZCAN_Receive_Data[5000];
            uint len = Method.ZCAN_GetReceiveNum(channel_handle_, 0);
            if (len > 0)
            {
                int size = Marshal.SizeOf(typeof(ZCAN_Receive_Data));
                IntPtr ptr = Marshal.AllocHGlobal((int)len * size);
                len = Method.ZCAN_Receive(channel_handle_, ptr, len, 50);
                for (int i = 0; i < len; i++)
                {
                    RecData[i] = (ZCAN_Receive_Data)Marshal.PtrToStructure(
                        (IntPtr)((Int64)ptr + i * size), typeof(ZCAN_Receive_Data));

                    for (int j = 0; j < 8; j++)
                    {
                        RecCanData[CircularBuff_rec.head].Data[j] = RecData[i].frame.data[j];
                    }
                    RecCanData[CircularBuff_rec.head].ID = RecData[i].frame.can_id;
                    RecCanData[CircularBuff_rec.head].RemoteFlag = 0;
                    RecCanData[CircularBuff_rec.head].ExternFlag = 0;
                    CircularBuff_rec.head = (ushort)((CircularBuff_rec.head + 1) % RECBUFFSIZE);
                    CircularBuff_rec.count = (ushort)(CircularBuff_rec.count + 1);
                    cancount.Text = "接收报文数量:" + CircularBuff_rec.count.ToString();
                }
                Marshal.FreeHGlobal(ptr);
            }
        }
        void ZLGAddErr()
        {
            ZCAN_CHANNEL_ERROR_INFO pErrInfo = new ZCAN_CHANNEL_ERROR_INFO();
            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(pErrInfo));
            Marshal.StructureToPtr(pErrInfo, ptr, true);
            if (Method.ZCAN_ReadChannelErrInfo(channel_handle_, ptr) != Define.STATUS_OK)
            {
                MessageBox.Show("获取错误信息失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                StateLog.Text = "设备异常";
                StateLog.BackColor = Color.Crimson;
                StateLog.ForeColor = Color.White;
            }
            Marshal.FreeHGlobal(ptr);
        }
        byte GetCanStateTick = 0;//获取can设备状态的tick
        bool CanConAgainFlag = false;//CAN 重新连接标志位
        /// <summary>
        /// 定时器任务100ms,周期轮询CAN报文
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_rec_Tick(object sender, EventArgs e)
        {

            if (++GetCanStateTick > 10)
            {
                GetCanStateTick = 0;  
                
                if(m_bOpen == 1)
                {
                    if(candevtype == 0)
                    {

                    }
                    /*
                    if (candevtype == 1)//PCAN
                    {
                        TPCANStatus stsResult = PCANBasic.GetStatus(m_PcanHandle);//获取Pcan状态检测
                        if (stsResult != TPCANStatus.PCAN_ERROR_OK)
                        {
                            CanDevConnection();
                            StateLog.Text = "设备异常";
                            StateLog.BackColor = Color.Crimson;
                            StateLog.ForeColor = Color.White;
                            CanConAgainFlag = true;
                        }
                    }
                    */
                    if(candevtype == 2)//ZLG
                    {
                        ZLGAddErr();
                    }
                }
                else if (CanConAgainFlag)
                {
                    CanConAgainFlag = false;
                    CanDevConnection();
                }
                
            }
           if( m_bOpen == 0)
                return;
            if (candevtype == 2)//ZLG
            {
                zlg_CanRec();
            }
            if (candevtype == 1)//PCAN
            {
                ReadMessages();
            }
            if (candevtype == 0)
            {
                my_push_rec();
            }
            
            if (GridViewRowsCnt > 450)  GridViewRowsCnt = 0;

            if (GridViewRowsCnt != lastgridview && GridViewRowsCnt > 20)
                dataGridViewcan.FirstDisplayedScrollingRowIndex = GridViewRowsCnt-20;
            lastgridview = GridViewRowsCnt;
        }
        void zlg_CanReset()
        {
            string path = channel_index_ + "/clear_auto_send";
            string value = "0";
            uint result = Method.ZCAN_SetValue(device_handle_, path, Encoding.ASCII.GetBytes(value));
            if (Method.ZCAN_ResetCAN(channel_handle_) != Define.STATUS_OK)
            {
                LogWork.Text = "提示:复位失败";
                return;
            }
        }
        private void button_StopCAN_Click(object sender, EventArgs e)
        {
            clear_fifo();
            if (m_bOpen == 0)
                return;
            if (candevtype == 0)
            {
                VCI_ResetCAN(m_devtype, m_devind, 0);
                VCI_ResetCAN(m_devtype, m_devind, 1);
                VCI_ClearBuffer(m_devtype, m_devind, 0);
                VCI_ClearBuffer(m_devtype, m_devind, 1);
                CanModeSelectedIndex = (byte)comboBox_Mode.SelectedIndex;
                VCI_INIT_CONFIG config = new VCI_INIT_CONFIG();
                config.AccCode = 0;
                config.AccMask = 4294967295;//OXFFFFFFFF
                config.Timing0 = CanBaudArr[0, comboBox_canbaud.SelectedIndex];
                config.Timing1 = CanBaudArr[1, comboBox_canbaud.SelectedIndex];
                config.Filter = 1;
                config.Mode = (byte)CanModeSelectedIndex;//0 正常 ;1 只听 ;2 自测
                VCI_InitCAN(m_devtype, m_devind, 0, ref config);
                VCI_InitCAN(m_devtype, m_devind, 1, ref config);
                VCI_StartCAN(m_devtype, m_devind, 0);
                VCI_StartCAN(m_devtype, m_devind, 1);
                LogWork.Text = "复位,并重新连接设备";
                LogWork.ForeColor = Color.Black;
            }
            if (candevtype == 1)
            {

            }
            if (candevtype == 2)
            {
                //zlg_CanReset();
            }
           
        }
        
        public void my_push_send(uint id, byte[] databuff, Int16 cnt)
        {
            string[] buff = new string[8];
            for (byte i = 0; i < 8; i++)
            {
                buff[i] = databuff[i].ToString("X2");
            }
            for (byte i = 0; i < cnt; i++)
            {
                if (CircularBuff_send.count < SENDBUFFSIZE)
                {
                    SendCanData[CircularBuff_send.head].ID = id;
                    SendCanData[CircularBuff_send.head].strbuff = string.Join(" ", buff); 
                    CircularBuff_send.head = (UInt16)((CircularBuff_send.head + 1) % SENDBUFFSIZE);
                    CircularBuff_send.count++;
                }
            }
            LogWork.Text = "0X" + id.ToString("X") + " " + string.Join(" ", buff);
        }
     
        public void my_push_send(uint id, string databuff, Int16 cnt)
        {
            for (byte i = 0; i < cnt; i++)
            {
                if (CircularBuff_send.count < SENDBUFFSIZE)
                {
                    SendCanData[CircularBuff_send.head].ID = id;
                    SendCanData[CircularBuff_send.head].strbuff = databuff;

                    CircularBuff_send.head = (UInt16)((CircularBuff_send.head + 1) % SENDBUFFSIZE);
                    CircularBuff_send.count++;
                }
            }
            LogWork.Text = "0X" + id.ToString("X")+ " " + databuff;
        }
        public CAN_ID_DATA my_pop_send()
        {
            CAN_ID_DATA databuff = SendCanData[CircularBuff_send.tail];
            CAN_ID_DATA Sendbuff_null = new CAN_ID_DATA()
            {
                ID = 0
            };
            if (CircularBuff_send.count == 0)
            {
                return Sendbuff_null;
            }
            CircularBuff_send.tail = (UInt16)((CircularBuff_send.tail + 1) % SENDBUFFSIZE);
            CircularBuff_send.count--;
            return databuff;
        }
        /// <summary>
        /// 线程:can发送报文
        /// </summary>
        unsafe public void my_can_send()//VCI_CAN_OBJ sendobj
        {     
            while (m_bOpen == 1)
            {
                lock (lockersend)
                {
                    byte cnt = 10;
                    while (CircularBuff_send.count > 0 && cnt > 0)
                    {
                        cnt--;
                        CAN_ID_DATA str_temp = my_pop_send();                      
                        if (/*str_temp.ID > 0 &&*/ BmuBootStateCheckCmdfun(str_temp))
                        {
                            VCI_CAN_OBJ sendobj = new VCI_CAN_OBJ();
                            sendobj.RemoteFlag = NowRemoteSelectedIndex;
                            sendobj.ExternFlag = NowExternSelectedIndex;
                            sendobj.ID = Convert.ToUInt32(str_temp.ID);
                            sendobj.DataLen = 8;
                            int len = 0,i = 0;
                            string[] sArray = str_temp.strbuff.Split(' ');

                            for ( i = 0; i < 8; i++)
                            {
                                sendobj.Data[i] = Convert.ToByte("0x"+sArray[i],16);
                            }
                            if(candevtype == 0)
                            {
                                len = VCI_Transmit(m_devtype, m_devind, m_canind, ref sendobj, 1);
                                //if (len == 0)
                                //{
                                //    len = VCI_Transmit(m_devtype, m_devind, m_canind, ref sendobj, 1);
                                //}
                            }
                            if (candevtype == 1)
                            {
                                len = (int)WriteFrame(sendobj);
                                //if (len != (int)TPCANStatus.PCAN_ERROR_OK)
                                //{
                                //    len = (int)WriteFrame(sendobj);
                                //}
                            }
                            if (candevtype == 2)
                            {
                                len = (int)zlg_CanSend(sendobj);
                                //if (len == 0)
                                //{
                                //    len = (int)zlg_CanSend(sendobj);
                                //}
                            }
                            if ( canMessage_stop == 0 ||(candevtype == 1 && len != (int)TPCANStatus.PCAN_ERROR_OK))
                            {
                                if (++GridViewRowsCnt > 490) GridViewRowsCnt = 0;
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[0].Value = System.Convert.ToString(GridViewRowsCnt);
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[1].Value = "发送";
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[2].Value = DateTime.Now.ToString("G");
                                if (candevtype == 0|| candevtype == 2)
                                {
                                    if (len > 0)
                                        dataGridViewcan.Rows[GridViewRowsCnt].Cells[3].Value = "成功";
                                    else
                                        dataGridViewcan.Rows[GridViewRowsCnt].Cells[3].Value = "失败";
                                }    
                                if (candevtype == 1 )
                                {
                                    if (len == (int)TPCANStatus.PCAN_ERROR_OK)
                                        dataGridViewcan.Rows[GridViewRowsCnt].Cells[3].Value = "成功";
                                    else
                                        dataGridViewcan.Rows[GridViewRowsCnt].Cells[3].Value = "失败";
                                }
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[4].Value = "0x" + str_temp.ID.ToString("X");
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[5].Value = (string)comboBox_Extern.Items[NowExternSelectedIndex];
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[6].Value = (string)comboBox_Remote.Items[NowRemoteSelectedIndex];
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[7].Value = "0x08";
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[8].Value = str_temp.strbuff;
                            }  
                        }
                    }    
                }
                Thread.Sleep(10);
            }  
        }
        unsafe private TPCANStatus WriteFrame(VCI_CAN_OBJ pSend)
        {
            TPCANMsg CANMsg= new TPCANMsg();
            // We create a TPCANMsg message structure 
            //
            CANMsg.DATA = new byte[8];

            // We configurate the Message.  The ID,
            // Length of the Data, Message Type
            // and the data
            //
            CANMsg.ID = pSend.ID;
            CANMsg.LEN = pSend.DataLen;
            CANMsg.MSGTYPE =  TPCANMessageType.PCAN_MESSAGE_STANDARD;
            // If a remote frame will be sent, the data bytes are not important.
            //
            
            // We get so much data as the Len of the message
            //
            for (int i = 0; i < CANMsg.LEN; i++)
            {   
                CANMsg.DATA[i] = pSend.Data[i];
            }
            // The message is sent to the configured hardware
            //
            return PCANBasic.Write(m_PcanHandle, ref CANMsg);
        }

        /// <summary>
        /// Function for reading CAN messages on normal CAN devices
        /// </summary>
        /// <returns>A TPCANStatus error code</returns>
        unsafe private TPCANStatus ReadMessage()
        {
            TPCANMsg CANMsg;
            TPCANTimestamp CANTimeStamp;
            TPCANStatus stsResult;
            
            // We execute the "Read" function of the PCANBasic                
            //
            stsResult = PCANBasic.Read(m_PcanHandle, out CANMsg, out CANTimeStamp);
            if (stsResult != TPCANStatus.PCAN_ERROR_QRCVEMPTY && CircularBuff_rec.count < RECBUFFSIZE)
            {
                // We process the received message
                //
                //ProcessMessage(CANMsg, CANTimeStamp);CANMsg
                for (int i = 0; i < 8; i++)
                {
                    RecCanData[CircularBuff_rec.head].Data[i] = CANMsg.DATA[i];
                }
                RecCanData[CircularBuff_rec.head].ID = CANMsg.ID;
                CircularBuff_rec.head = (ushort)((CircularBuff_rec.head + 1) % RECBUFFSIZE);
                CircularBuff_rec.count = (ushort)(CircularBuff_rec.count + 1);
                cancount.Text = "接收报文数量:" + CircularBuff_rec.count.ToString();
            }
                    
            return stsResult;
        }
        private void ReadMessages()
        {
            TPCANStatus stsResult;

            // We read at least one time the queue looking for messages.
            // If a message is found, we look again trying to find more.
            // If the queue is empty or an error occurr, we get out from
            // the dowhile statement.
            //			
            do
            {
                stsResult = ReadMessage();
                if (stsResult == TPCANStatus.PCAN_ERROR_ILLOPERATION)
                    break;
            } while ( (!Convert.ToBoolean(stsResult & TPCANStatus.PCAN_ERROR_QRCVEMPTY)));//ToBoolean(number)  0 false ;不为0 (-/+) true;
        }
        public void my_push_rec()
        {
            uint temp1, temp2;
            VCI_CAN_OBJ[] RecData = new VCI_CAN_OBJ[2000];
            if (CircularBuff_rec.count < RECBUFFSIZE)
            {
                UInt32 res = VCI_Receive(m_devtype, m_devind, m_canind, ref RecData[0], RECBUFFSIZE, 0);

                if (res == 0xFFFFFFFF)
                    res = 0;
                if (res > 0)
                {
                    cancount.Text = "接收报文数量:" + res.ToString();

                    // 防止丢包和可能出现的数据越界
                    if (CircularBuff_rec.head + res <= RECBUFFSIZE)
                        Array.Copy(RecData, 0, RecCanData, CircularBuff_rec.head, res);
                    else
                    {
                        temp1 = RECBUFFSIZE - CircularBuff_rec.head;
                        temp2 = res - (RECBUFFSIZE - CircularBuff_rec.head);
                        Array.Copy(RecData, 0, RecCanData, CircularBuff_rec.head, temp1);
                        Array.Copy(RecData, temp1, RecCanData, 0, temp2);
                    }
                    CircularBuff_rec.head = ((ushort)((CircularBuff_rec.head + res) % RECBUFFSIZE));
                    CircularBuff_rec.count = (ushort)(CircularBuff_rec.count + res);
                }
            }
        }
        public VCI_CAN_OBJ my_pop_rec()
        {
            VCI_CAN_OBJ databuff = RecCanData[CircularBuff_rec.tail];
            VCI_CAN_OBJ databuff_null = new VCI_CAN_OBJ()
            {
                ID = 0
            };
            if (CircularBuff_rec.count > 0)
            {
                CircularBuff_rec.tail = (UInt16)((CircularBuff_rec.tail + 1) % RECBUFFSIZE);
                CircularBuff_rec.count--;
            }
            else
            {
                return databuff_null;
            }
            return databuff;
        }
         private void button_Send_Click(object sender, EventArgs e)
        {
            short cnt = 1;
            if (m_bOpen == 0)
                return;
            if (textBox1.Text == "")
                textBox1.Text = "1";
            cnt = Convert.ToInt16(textBox1.Text);
            my_push_send(Convert.ToUInt32("0x" + textBox_ID.Text, 16), textBox_Data1.Text, cnt);
            LogWork.Text = "发送数据:" + textBox_Data1.Text + ";次数:" + textBox1.Text;
            LogWork.ForeColor = Color.Black;

        }
       
       
        public void setStartSend(uint en)
        {
            if (en == 1)
            {   //新建一个线程
                sendv_thread_ = new Thread(my_can_send);
                sendv_thread_.IsBackground = true;
                sendv_thread_.Start();
            }
            else if (sendv_thread_ != null)
            {
                sendv_thread_.Join();//关闭这个线程
                sendv_thread_ = null;
            }
        }
        public void setStartRec(uint en)
        {
            if (en == 1)
            {
                recv_thread_ = new Thread(ProcessMessageCan);
                recv_thread_.IsBackground = true;
                recv_thread_.Start(/*listViewNodeList*/);
            }
            else if(recv_thread_ != null)//操作对象前先判断对象是否实例
            {           
                recv_thread_.Join();
                recv_thread_ = null;
            }
        }
        /// <summary>
        /// 线程:can解包
        /// </summary>
        /// <param name="obj"></param>
        unsafe protected void ProcessMessageCan(object obj)
        {
            byte i = 0;
            byte cnt;
            VCI_CAN_OBJ TempCanData = new VCI_CAN_OBJ();
            byte[] arrybuff = new byte[8];
            string[] strarry = new string[8];
            while (m_bOpen == 1)
            {
                lock (locker)
                {
                    cnt = 20;
                    while (CircularBuff_rec.count > 0 && cnt > 0)
                    {
                        cnt--;
                        TempCanData = my_pop_rec();
                        if (TempCanData.ID > 0)
                        {
                            for (i = 0; i < 8; i++)
                            {
                                strarry[i] = TempCanData.Data[i].ToString("X2"); 
                                arrybuff[i] = TempCanData.Data[i];
                            }
                            CanInSlaveModeAck(TempCanData.ID, arrybuff);
                            CanBootRecAck(TempCanData.ID, arrybuff);
                            GetDevCanDBCdata(TempCanData.ID, arrybuff);
                            Clb_Reply(TempCanData.ID, arrybuff);
                            CanFaultlogRecSever(TempCanData.ID, arrybuff);
                            if (DBCstartFlag == 1)
                            {
                                //ProcessDBCserve();
                            }
                            if ( canMessage_stop == 0 && TempCanData.ID >= CanIDfiltrationMIN && TempCanData.ID <= CanIDfiltrationMAX)
                            {
                               
                                if (++GridViewRowsCnt > 490) GridViewRowsCnt = 0;
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[0].Value = GridViewRowsCnt.ToString();
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[1].Value = "接收";
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[2].Value = DateTime.Now.ToString("G");
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[3].Value = "成功";
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[4].Value = "0x" + TempCanData.ID.ToString("X");

                                if (TempCanData.RemoteFlag == 0)
                                    dataGridViewcan.Rows[GridViewRowsCnt].Cells[5].Value = "数据帧 ";
                                else
                                    dataGridViewcan.Rows[GridViewRowsCnt].Cells[5].Value = "远程帧 ";
                                if (TempCanData.ExternFlag == 0)
                                    dataGridViewcan.Rows[GridViewRowsCnt].Cells[6].Value = "标准帧 ";
                                else
                                    dataGridViewcan.Rows[GridViewRowsCnt].Cells[6].Value = "扩展帧 ";
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[7].Value = "0x08";
                                dataGridViewcan.Rows[GridViewRowsCnt].Cells[8].Value = string.Join(" ", strarry);
                            }    
                        }
                    }
                }
                Thread.Sleep(10);
            }
        }
        private string GetStr(string TxtStr, string FirstStr, string SecondStr)
        {
            if (FirstStr.IndexOf(SecondStr, 0) != -1)
                return "";
            int FirstSite = TxtStr.IndexOf(FirstStr, 0);
            int SecondSite = TxtStr.IndexOf(SecondStr, FirstSite + 1);
            if (FirstSite == -1 || SecondSite == -1)
                return "";
            return TxtStr.Substring(FirstSite + FirstStr.Length, SecondSite - FirstSite - FirstStr.Length);
        }
        /// <summary>
        ///从字符串数组ControlFun里面里提取功能控制的列表
        /// </summary>
        void GetTreeView_ControlFun()
        {
            MyDefine Myd = new MyDefine();
            TreeNode REL_Control = new TreeNode();
            TreeNode IO_Control = new TreeNode();
            REL_Control = treeView1_fun.Nodes.Add("继电器控制");
            IO_Control = treeView1_fun.Nodes.Add("IO口控制");
            foreach (string st in Myd.ControlFun)
            {
                String[] sArray = st.Split('-');
                if(sArray.Length > 1)
                {
                    if (st.Contains("继电器"))
                        REL_Control.Nodes.Add(sArray[0].PadRight(50));
                    if (st.Contains("PT"))
                        IO_Control.Nodes.Add(sArray[0].PadRight(50));
                }
            }           
        }
        void ProcessDBCserve()
        {
            TreeNode rootNode = new TreeNode();
            string str;
            string [] dbctype  = new String [10];
            ushort i,j,k = 0;
            StreamReader sR4 = new StreamReader(dbcFileName, Encoding.GetEncoding("gb2312"));

            for(i = 0;i< dbcCM_Line; i++)
            {
                str = sR4.ReadLine();
                if (str.Contains("BU_:") && k == 0)
                {
                    k = 1;
                    string[] sArray = str.Split(' ');
                    for (j = 0; j < sArray.Length; j++)
                        if (sArray.Length - j>1)
                        {
                            dbctype[j] = sArray[j+1];
                        }
                }
               
                if (str.Contains("BO_") && k == 1)
                {
                    if (str.Contains("CM_"))
                    {

                    }
                    else
                    {
                        string[] sArray = str.Split(' ');
                        if (sArray.Length > 1)
                        {
                            uint temp = Convert.ToUInt32(sArray[1]) & 0xFFF;
                            string temp_id = "0x" + temp.ToString("X2");
                            double second = DateTime.Now.TimeOfDay.TotalSeconds;
                            rootNode = treeView_dbc.Nodes.Add(second.ToString().PadRight(20) + temp_id.PadRight(15) + sArray[2].PadRight(35) + sArray[3]);
                            k = 2;
                        }
                    }
                        
                }
                if(str.Contains("SG_") && k == 2)
                {
                    string[] nameArray = str.Split(' ');//名字
                    string[] unitArray = str.Split('"');//单位
                    string commentArray = "", unittest = "";//注释
                    string temp = nameArray[2];

                    
                    StreamReader sR1 = new StreamReader(dbcFileName, Encoding.GetEncoding("gb2312"));
                    string str_CM;
                    if (unitArray.Length > 1)
                        unittest = unitArray[1];
                    for (j = 0; j < dbcBA_DEF_Line; j++)//comment
                    {
                        str_CM = sR1.ReadLine();
                        if (str_CM.Contains(temp) && str_CM.Contains("CM_"))
                        {
                            string[] str_Array = str_CM.Split('"');
                            if (str_Array.Length > 1)
                                commentArray = str_Array[1];
                            break;
                        }
                    }  
                    sR1.Close();
                    
                    
                    temp = temp.PadRight(25) + unittest.PadRight(10) + commentArray.PadRight(40);
                    rootNode.Nodes.Add(temp);
                    
                }
                if (str == "" && k == 2)
                {
                    k = 1;      
                }
            }
            sR4.Close();
        }
        void clear_fifo()
        {
            GridViewRowsCnt = 0;
            clear_fifo_send();
            clear_fifo_rec();
        }                                          
        void clear_fifo_send()
        {
            CircularBuff_send.count = 0;
            CircularBuff_send.head = 0;
            CircularBuff_send.tail = 0;
        }
        void clear_fifo_rec()
        {
            CircularBuff_rec.count = 0;
            CircularBuff_rec.head = 0;
            CircularBuff_rec.tail = 0;
        }
        private void toolStripMenuItemclear_Click(object sender, EventArgs e)
        {
            if (MouseLocation == 1)
            {
                dataGridViewcan.Rows.Clear();
                clear_fifo();
                dataGridViewcan.Rows.Add(500);
            }
            if (MouseLocation == 3)
            {
                dataGridViewErr.Rows.Clear();
                ErrorLogCnt = 0;
                Array.Clear(BMS_GB_FaultInfomation, 0, 10);
                Array.Clear(BMS_FaultInfomation, 0, 16);
                
            }
        }

        int ArraySequenceEqual(byte[] sBuffer, byte sindex,byte[] dBuffer, byte dindex, byte length)
        {
            for(byte i = 0;i<length;i++)
            {
                try
                {
                    if (sBuffer[i + sindex] != dBuffer[i + dindex])
                        return 0;
                }
                catch
                {
                    return 0;
                }
            }
            return 1;
        }
       
        void ReadLicenseHex()
        {
            byte[] DataBuffer = new byte[32];
            byte[] tempBuffer = new byte[32];
            byte[] check1 = new byte[16] { 0x20, 0x07, 0xc8, 0x05, 0x02, 0x00, 0x00, 0x00, 0x08, 0x12, 0x00, 0x20, 0x06, 0x48, 0x80, 0x47 };
            byte[] check2 = new byte[12] { 0xFE, 0xE7, 0xFE, 0xE7, 0xFE, 0xE7, 0xFE, 0xE7, 0xFE, 0xE7, 0xFE, 0xE7 };
            string HEXFilePath;

            HEXFilePath = System.AppDomain.CurrentDomain.BaseDirectory+"RJETBMS.bin";
            if (File.Exists(HEXFilePath))
            {
                uint j = 0;
                uint temp = (uint)new FileInfo(HEXFilePath).Length;
                UInt16 read_data_num = 0;

                for (UInt32 AddrOffset = 0; AddrOffset < temp;j++)
                {
                    BinaryReader br = new BinaryReader(new FileStream(HEXFilePath, FileMode.Open));                  
                    Array.Clear(DataBuffer, 0, 32);
                    Array.Clear(tempBuffer, 0, 32);
                    uint CheckRecLine = 0;
                    uint readlicensecnt = 0;
                    br.BaseStream.Seek((int)AddrOffset, SeekOrigin.Begin);
                    read_data_num = (UInt16)br.Read(DataBuffer, 0, 32);
                    if (1 == ArraySequenceEqual(DataBuffer, 20, check2, 0, 12))
                    {
                        CheckRecLine = 1;
                        Array.Copy(DataBuffer, tempBuffer, 32);
                        if (1 == ArraySequenceEqual(DataBuffer, 0, check1, 0, 16))
                        {
                            if(DataBuffer[16]>= DataBuffer[0] && DataBuffer[17] >= DataBuffer[1] && DataBuffer[18] >= DataBuffer[2] && userLicensecnt == 0)
                            {
                                readlicensecnt = (uint)((DataBuffer[16] - DataBuffer[0]) *100 + (DataBuffer[17] - DataBuffer[1]) * 10 + (DataBuffer[18] - DataBuffer[2]));
                                if (readlicensecnt < 365)
                                {
                                    userLicensecnt = readlicensecnt;
                                }
                            }         
                        }
                    }  
                    br.Close();
                    
                    if (CheckRecLine == 1)
                    {
                        BinaryWriter bw = new BinaryWriter(new FileStream(HEXFilePath, FileMode.Open));
                        if (readlicensecnt > 0 && readlicensecnt < 365)
                        {
                            if (tempBuffer[18] > tempBuffer[2]) tempBuffer[18]--;
                            else if (tempBuffer[17] > tempBuffer[1]) tempBuffer[17]--;
                            else if (tempBuffer[16] > tempBuffer[0]) tempBuffer[10]--;
                        }
                        else
                        {
                            if (tempBuffer[18] > 0) tempBuffer[18]--;
                            else if (tempBuffer[17] > 0) tempBuffer[17]--;
                            else if (tempBuffer[16] > 0) tempBuffer[10]--;
                        }
                        
                        bw.Seek((int)AddrOffset, SeekOrigin.Begin);
                        bw.Write(tempBuffer);
                        bw.Close();
                        if (userLicensecnt > 0)
                        {
                            updata_linsece();
                            LogWork.Text = "校验秘钥成功";
                        }
                    }
                    AddrOffset += read_data_num;
                }

                if (userLicensecnt > 0)
                {
                    updata_linsece();
                    LogWork.Text = "校验秘钥成功";
                }
                else
                {
                    LogWork.Text = "校验秘钥失败";
                }
            }
            else
            {
                LogWork.Text = "文件缺失";
            } 
        }

        uint LibCal_Crc32Single(byte data, uint CRC_Init, uint factor)
        {
            uint crc32;
            uint i;

            crc32 = CRC_Init;
            crc32 ^= (((uint)((data))) << 24);

            for (i = 0; i < 8; i++)
            {
                if ((crc32 & 0x80000000) != 0)
                {
                    crc32 <<= 1;
                    crc32 ^= factor;
                }
                else
                {
                    crc32 <<= 1;
                }
            }
            return crc32;
        }
        /******************************************************************************
        //u32Crc = LibCal_Crc32Multi(arruy, 4, CRC32_INIT, CRC32_FACTOR);    //CRC32_INIT = 0x5648 ; CRC32_FACTOR =  0x04C11DB7;
        *******************************************************************************/
        uint LibCal_Crc32Multi(byte[] data, uint len, uint CRC_Init, uint factor)
        {
            uint crc32;
            uint i;

            crc32 = CRC_Init;

            for (i = 0; i < len; i++)
            {
                crc32 = LibCal_Crc32Single(data[i], crc32, factor);
            }

            return crc32;
        }
        uint LibCal_Crc32Multi(byte[] data, uint index,uint len, uint CRC_Init, uint factor)
        {
            uint crc32;
            uint i;

            crc32 = CRC_Init;

            for (i = index; i < index + len; i++)
            {
                crc32 = LibCal_Crc32Single(data[i], crc32, factor);
            }

            return crc32;
        }
        /// <summary>
        /// 改变单体电芯电压温度图标
        /// </summary>
        public void ChangeCellBatteryVolOrTempColor()
        {
            System.Windows.Forms.Label volimage = new System.Windows.Forms.Label();
            System.Windows.Forms.Label tempimage = new System.Windows.Forms.Label();
            UInt16 u16_CellVolt = 0, u16_CellTemp = 0;
            try
            {
                for (byte i = 0; i < BMS_PAGECELLNUMBER_Max; i++)
                {
                    if (i < BMS_BMUCellNum)
                    {
                        u16_CellVolt = (UInt16)(Convert.ToDouble(CellInfo[i].cellvoltext) * 1000);
                        
                        if (cellLevel.VOL_LV1min <= u16_CellVolt && u16_CellVolt <= cellLevel.VOL_LV1max)
                        {
                            volimage.Image = Properties.Resources.Battery1_30;
                        }
                        if (cellLevel.VOL_LV2min <= u16_CellVolt && u16_CellVolt <= cellLevel.VOL_LV2max)
                        {
                            volimage.Image = Properties.Resources.Battery2_30;
                        }
                        if (cellLevel.VOL_LV3min <= u16_CellVolt && u16_CellVolt <= cellLevel.VOL_LV3max)
                        {
                            volimage.Image = Properties.Resources.Battery3_30;
                        }
                        if (cellLevel.VOL_LV4min <= u16_CellVolt && u16_CellVolt <= cellLevel.VOL_LV4max)
                        {
                            volimage.Image = Properties.Resources.Battery4_30;
                        }
                        //更新温度图标
                        if(CellInfo[i].celltemptext == "-")
                        {
                            tempimage.Image = Properties.Resources.T4_30;
                        }
                        else
                        {
                            u16_CellTemp = (UInt16)(Convert.ToInt16(CellInfo[i].celltemptext) + 40);
                            if (cellLevel.TEMP_LV1min <= u16_CellTemp && u16_CellTemp <= cellLevel.TEMP_LV1max)
                            {
                                tempimage.Image = Properties.Resources.T1_30;
                            }
                            if (cellLevel.TEMP_LV2min <= u16_CellTemp && u16_CellTemp <= cellLevel.TEMP_LV2max)
                            {
                                tempimage.Image = Properties.Resources.T2_30;
                            }
                            if (cellLevel.TEMP_LV3min <= u16_CellTemp && u16_CellTemp <= cellLevel.TEMP_LV3max)
                            {
                                tempimage.Image = Properties.Resources.T3_30;
                            }
                            if (cellLevel.TEMP_LV4min <= u16_CellTemp && u16_CellTemp <= cellLevel.TEMP_LV4max)
                            {
                                tempimage.Image = Properties.Resources.T4_30;
                            }
                        }
                        
                    }
                    CellInfo[i].VolIcon = volimage.Image;
                    CellInfo[i].TempIcon = tempimage.Image; 
                }
            }
            catch { }
        }
        public void ChangePCBTempColor()
        {
            System.Windows.Forms.Label myimage = new System.Windows.Forms.Label();
            try
            {
                for (byte i = 0; i < 32; i++)
                {
                    myimage = PCBTemplabel[i];
                    if (cellLevel.TEMP_LV1min < BMS_CSC_PCB_Temp[i] && BMS_CSC_PCB_Temp[i] <= cellLevel.TEMP_LV1max)
                    {
                        myimage.Image = Properties.Resources.T1_30;
                    }
                    if (cellLevel.TEMP_LV2min < BMS_CSC_PCB_Temp[i] && BMS_CSC_PCB_Temp[i] <= cellLevel.TEMP_LV2max)
                    {
                        myimage.Image = Properties.Resources.T2_30;
                    }
                    if (cellLevel.TEMP_LV3min < BMS_CSC_PCB_Temp[i] && BMS_CSC_PCB_Temp[i] <= cellLevel.TEMP_LV3max)
                    {
                        myimage.Image = Properties.Resources.T3_30;
                    }
                    if (cellLevel.TEMP_LV4min < BMS_CSC_PCB_Temp[i] && BMS_CSC_PCB_Temp[i] <= cellLevel.TEMP_LV4max)
                    {
                        myimage.Image = Properties.Resources.T4_30;
                    }
                }
            }
            catch { }
        }
        /// <summary>
        /// 更新电芯信息编号
        /// </summary>
        public void writebBMSCellnum()
        {
            int cellnumsoure = (BMS_CellVoltTempPage - 1)* BMS_BMUCellNum  + 1;
            try
            {
                for (byte cellnum = 0; cellnum < BMS_PAGECELLNUMBER_Max; cellnum++)
                {
                    int temp = cellnum + BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1);
                    
                    if (cellnum >= BMS_BMUCellNum  )
                        CellInfo[cellnum].cellnumtext = "-";
                    else 
                    {      
                        CellInfo[cellnum].cellnumtext = cellnumsoure.ToString();
                        cellnumsoure++;
                    }
                }
                for (byte pagenum = 0; pagenum < 8; pagenum++)
                {
                    if (pagenum + 1 == BMS_CellVoltTempPage)
                    {
                        bt_PackNum[pagenum].Image = Properties.Resources.储能柜green;
                        bt_PackNum[pagenum].ForeColor = Color.FromArgb(14, 147, 46);
                    }
                    else
                    {
                        bt_PackNum[pagenum].Image = Properties.Resources.储能柜black;
                        bt_PackNum[pagenum].ForeColor = Color.Black;
                    }

                }
            }
            catch { }
        }
        public void WriteBMSCellInfo()
        {
            try
            {
                int temp = BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1);
                int offset = 0;
                for (byte cellnum = 0; cellnum < BMS_PAGECELLNUMBER_Max; cellnum++)//BMS_PAGECELLNUMBER_Max
                {
                    
                    if (cellnum >= BMS_BMUCellNum )
                    {
                        CellInfo[cellnum].cellinfoVisible = false;
                    }
                    else
                    {
                        CellInfo[cellnum].cellinfoVisible = true;
                        
                        while (BMS_CellVolt[temp + offset] == 0)//下位机发送单体电压0,
                        {
                            offset++;
                        }
                        
                        CellInfo[cellnum].CellNumReal = (UInt16)offset;
                        //单体电压
                        if (cellinfocanouttime == 0)
                            CellInfo[cellnum].cellvoltext = "-";
                        else
                            CellInfo[cellnum].cellvoltext = (0.001 * BMS_CellVolt[temp + offset]).ToString("0.000");//显示3位有效小数
                        //单体温度
                        
                        if (BMS_ClusterTemp[temp + offset] == 0 || cellinfocanouttime == 0)
                            CellInfo[cellnum].celltemptext = "-";
                        else
                            CellInfo[cellnum].celltemptext = (BMS_ClusterTemp[temp + offset] - 40).ToString();
                    }
                    //均衡状态
                    if (DV_BMS_Cell_BALA_FB[temp + offset] == 0|| cellinfocanouttime == 0)
                    {
                        CellInfo[cellnum].cellstatetext = "均衡未开";
                    }
                    else
                    {
                        CellInfo[cellnum].cellstatetext = "均衡已开";
                    }
                    offset++;
                }
            }
            catch { }
        }
        void WriteBMSPCBTemp()
        {
            try
            {
                foreach (Control Panel in flowLayoutPanel2.Controls)
                {
                    foreach (System.Windows.Forms.Label label in Panel.Controls)
                    {
                        string st = label.Name.ToString();
                        if (st.Contains("BMS_PCB_Temp"))
                        {
                            string[] sArray = st.Split('p');
                            label.Text = (BMS_CSC_PCB_Temp[(Convert.ToByte(sArray[1]) - 1)] - 40).ToString();
                        }
                    }
                }
            }
            catch { }
        }
        uint cellinfocanouttime = 50;
        /// <summary>
        /// 按照DBC协议解包
        /// </summary>
        /// <param name="id"></param>
        /// <param name="arry"></param>
        public void GetDevCanDBCdata(uint id, byte[] arry)
        {
            if ((uint)MyDefine.DBC_ID.BMS_OtherSup == id)
            {
                DBCData.BMS_1P5V_MSR = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_LV12V_MSR = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_VREF = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_HALL_OUT_MSR = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_PowerSup == id)
            {
                DBCData.BMS_LV24_MSR = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_Wakeup_MSR = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_RLY_POS_MSR = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_5V_MSR = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_PackVolt == id)
            {
                DBCData.BMS_BattVolt = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_LinkPOStoPackNEGVolt1 = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.LINK_NEG_MsrVolt = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_LinkPOStoPackNEGVolt2 = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_Current == id)
            {
                DBCData.BMS_Cluster_Curr = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_CAN_HALL_Curr = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_AD_HALL_Current = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_Shunt_Current = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_BattContLight_Sts == id)
            {
                DBCData.BMS_DI_HSD1Sts = (byte)((arry[0] >> 0) & 0x01);
                DBCData.BMS_DI_HSD2Sts = (byte)((arry[0] >> 1) & 0x01);
                DBCData.BMS_DI_HSD3Sts = (byte)((arry[0] >> 2) & 0x01);
                DBCData.BMS_DI_LSD1Sts = (byte)((arry[0] >> 3) & 0x01);
                DBCData.BMS_DI_LSD2Sts = (byte)((arry[0] >> 4) & 0x01);
                DBCData.BMS_DI_LSD3Sts = (byte)((arry[0] >> 5) & 0x01);
                DBCData.BMS_DI_LSD4Sts = (byte)((arry[0] >> 6) & 0x01);
                DBCData.BMS_PreRlyDriveCmd = (byte)((arry[0] >> 7) & 0x01);
                DBCData.BMS_NegRlyDriveCmd = (byte)((arry[1] >> 0) & 0x01);
                DBCData.BMS_PosRlyDriveCmd = (byte)((arry[1] >> 1) & 0x01);
                DBCData.EMS_NEG_Cont_Cmd = (byte)((arry[1] >> 2) & 0x01);
                DBCData.EMS_NEG_Cont_Cmd_Valid = (byte)((arry[1] >> 3) & 0x01);
                DBCData.EMS_POS_Cont_Cmd = (byte)((arry[1] >> 4) & 0x01);
                DBCData.EMS_POS_Cont_Cmd_Valid = (byte)((arry[1] >> 5) & 0x01);
                DBCData.EMS_PRECHG_Cont_Cmd = (byte)((arry[1] >> 6) & 0x01);
                DBCData.EMS_PRECHG_Cont_Cmd_Valid = (byte)((arry[1] >> 7) & 0x01);
                DBCData.Green_Light_Sts = (byte)((arry[2] >> 1) & 0x01);
                DBCData.Red_Light_Sts = (byte)((arry[2] >> 2) & 0x01);
                DBCData.BMS_BattSts = arry[3];
                FacCheckSucceeFlag = true;
            }
            if ((uint)MyDefine.DBC_ID.BMS_EnvirTemp == id)
            {
                DBCData.BMS_EnvirTemp_1 = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_EnvirTemp_2 = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_EnvirTemp_3 = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_EnvirTemp_4 = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_EnvirTempMaxMin_Shunt == id)
            {
                DBCData.BMS_EnvirTemp_Max = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_EnvirTemp_Min = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_ShuntTemp_1 = (ushort)(arry[6] << 8 | arry[7]);
                DBCData.BMS_EnvirNumTemp_Max = arry[4];
                DBCData.BMS_EnvirNumTemp_Min = arry[5];     
            }
            if ((uint)MyDefine.DBC_ID.BMS_BMCTemp_CSCMaxMin == id)
            {
                DBCData.BMS_BCU_PCB_Temp = arry[0];
                DBCData.BMS_CSC_PCB_MaxTemp = arry[1];
                DBCData.BMS_CSC_PCB_MaxTempNum = arry[2];
                DBCData.BMS_CSC_PCB_MinTemp = arry[3];
                DBCData.BMS_CSC_PCB_MinTempNum = arry[4];
            }
            if ((uint)MyDefine.DBC_ID.BMS_ContactorSup1 == id)
            {
                DBCData.BMS_ISO_5V_MSR = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_HSD_RLY_POS_MSR = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_HSD_RLY_NEG_MSR = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_LSD_RLY_POS_MSR = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_ContactorSup2 == id)
            {
                DBCData.BMS_PRECHG_relay_Dia_Curr = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_POS_relay_Dia_Curr = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_NEG_relay_Dia_Curr = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_LSD_RLY_NEG_MSR = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_DiagVolt == id)
            {
                DBCData.BMS_POS_HIGH_FAULT_MSR = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_NEG_HIGH_FAULT_MSR = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_PRECHG_HIGH_FAULT_MSR = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_HALL12V_HIGH_FAULT_MSR = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_HSDVolt == id)
            {
                DBCData.BMS_HSD_OUT1_FAULT_MSR = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_HSD_OUT2_FAULT_MSR = (ushort)(arry[2] << 8 | arry[3]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_CellVoltMaxMin1 == id)
            {
                DBCData.BMS_CellVoltMax1 = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_NumberCellVoltMax1 = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_CellVoltMin1 = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_NumberCellVoltMin1 = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_CellVoltMaxMin2 == id)
            {
                DBCData.BMS_CellVoltMax2 = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_NumberCellVoltMax2 = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_CellVoltMin2 = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_NumberCellVoltMin2 = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_CellVoltMaxMin3 == id)
            {
                DBCData.BMS_CellVoltMax3 = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_NumberCellVoltMax3 = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_CellVoltMin3 = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_NumberCellVoltMin3 = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_AFEVoltMaxMin == id)
            {
                DBCData.BMS_AFEMaxVolt = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_NumberAFEMaxVolt = arry[2];
                DBCData.BMS_AFEMinVolt = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_NumberAFEMinVolt = arry[6];
            }
            if ((uint)MyDefine.DBC_ID.BMS_FaultInfomation1 == id)
            {
                Array.Copy(arry, 0, BMS_FaultInfomation, 0, 8);   
            }
            if ((uint)MyDefine.DBC_ID.BMS_FaultInfomation2 == id)
            {
                Array.Copy(arry, 0, BMS_FaultInfomation, 8, 8);
                
            }
            if ((uint)MyDefine.DBC_ID.EOL_Test == id)
            {
                DBCData.EOL_ModelCont = (byte)((arry[0] >> 0) & 0x01);
                DBCData.EOL_FanCont = (byte)((arry[0] >> 2) & 0x01);

                DBCData.EOL_MainPosCont = (byte)((arry[1] >> 0) & 0x01);
                DBCData.EOL_MainNegCont = (byte)((arry[1] >> 1) & 0x01);
                DBCData.EOL_PreCont = (byte)((arry[1] >> 2) & 0x01);
                DBCData.EOL_RedLight = (byte)((arry[1] >> 3) & 0x01);
                DBCData.EOL_GreenLight = (byte)((arry[1] >> 4) & 0x01);
                DBCData.EOL_DryCont1 = (byte)((arry[1] >> 5) & 0x01);
                DBCData.EOL_DryCont2 = (byte)((arry[1] >> 6) & 0x01);
                DBCData.EOL_ShuntRelease = (byte)((arry[1] >> 7) & 0x01);

                DBCData.EOL_IsoDetCmd = arry[7];

            }
            if ((uint)MyDefine.DBC_ID.EOL_State == id)
            {
                DBCData.EOL_ModelState = (byte)((arry[0] >> 0) & 0x01);

                DBCData.EOL_MainPosCont_Res = (byte)((arry[1] >> 0) & 0x01);
                DBCData.EOL_MainNegCont_Res = (byte)((arry[1] >> 1) & 0x01);
                DBCData.EOL_PreCont_Res = (byte)((arry[1] >> 2) & 0x01);
                DBCData.EOL_RedLight_Res = (byte)((arry[1] >> 3) & 0x01);
                DBCData.EOL_GreenLight_Res = (byte)((arry[1] >> 4) & 0x01);
                DBCData.EOL_DryCont1_Res = (byte)((arry[1] >> 5) & 0x01);
                DBCData.EOL_DryCont2_Res = (byte)((arry[1] >> 6) & 0x01);
                DBCData.EOL_ShuntRelease_Res = (byte)((arry[1] >> 7) & 0x01);
            }
            if ((uint)MyDefine.DBC_ID.BMS_InletTempMaxMinAvg == id)
            {
                DBCData.BMS_InletMaxTemp = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_InletNumMaxTemp = arry[2];
                DBCData.BMS_InletMinTemp = (ushort)(arry[3] << 8 | arry[4]);
                DBCData.BMS_InletNumMinTemp = arry[5];
                DBCData.BMS_InletAvgTemp = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_OutletTempMaxMinAvg == id)
            {
                DBCData.BMS_OutletMaxTemp = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_OutletNumMaxTemp = arry[2];
                DBCData.BMS_OutletMinTemp = (ushort)(arry[3] << 8 | arry[4]);
                DBCData.BMS_OutletNumMinTemp = arry[5];
                DBCData.BMS_OutletAvgTemp = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_AFE_TempMaxMin == id)
            {
                DBCData.BMS_AFE_MaxTemp = arry[0];
                DBCData.BMS_AFE_MaxTempNum = arry[1];
                DBCData.BMS_AFE_MinTemp = arry[2];
                DBCData.BMS_AFE_MinTempNum = arry[3];
            }
            if ((uint)MyDefine.DBC_ID.BMS_SOX == id)
            {
                DBCData.BMS_SOH = (ushort)(arry[0] << 2 | arry[1] >> 6);
                DBCData.BMS_BattSOE = (ushort)((arry[1] & 0x3F) * 256 + arry[2]);
                DBCData.BMS_SOC = (ushort)(arry[3] << 2 | arry[4] >> 6);
                DBCData.BMS_CellMaxSOC = (ushort)((arry[4] & 0x3F) << 4 | arry[5] >> 4);
                DBCData.BMS_CellMinSOC = (ushort)((arry[5] & 0x0F) << 6 | arry[6] >> 2);
                DBCData.BMS_BattTrueSOC = (ushort)((arry[6] & 0x03) << 8 | arry[7]);  
            }
            if ((uint)MyDefine.DBC_ID.BMS_DTC_Isolation == id)
            {
                DBCData.BMS_IsolationR_Pos = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_IsolationR_Neg = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_IsolationR = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_DTCNumber = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_RTC == id)
            {
                DBCData.BMS_RTC_Year = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_RTC_Month = arry[2];
                DBCData.BMS_RTC_Day = arry[3];
                DBCData.BMS_RTC_Hour = arry[4];
                DBCData.BMS_RTC_Minute = arry[5];
                DBCData.BMS_RTC_Second = arry[6];
            }
            if ((uint)MyDefine.DBC_ID.BMS_Version == id)
            {
                DBCData.BMS_HWVersion = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_SWVersion = (UInt64)(arry[2] << 32 | arry[3] << 24 | arry[4] << 16 | arry[5] << 8 | arry[6]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_FAN_States == id)
            {
                BMS_FAN_States[0] = (byte)((arry[0] >> 0) & 0x01);
                BMS_FAN_States[1] = (byte)((arry[0] >> 1) & 0x01);
                BMS_FAN_States[2] = (byte)((arry[0] >> 2) & 0x01);
                BMS_FAN_States[3] = (byte)((arry[0] >> 3) & 0x01);
                BMS_FAN_States[4] = (byte)((arry[0] >> 4) & 0x01);
                BMS_FAN_States[5] = (byte)((arry[0] >> 5) & 0x01);
                BMS_FAN_States[6] = (byte)((arry[0] >> 6) & 0x01);
                BMS_FAN_States[7] = (byte)((arry[0] >> 7) & 0x01);

                BMS_FAN_States[8] = (byte)((arry[1] >> 0) & 0x01);
                BMS_FAN_States[9] = (byte)((arry[1] >> 1) & 0x01);
                BMS_FAN_States[10] = (byte)((arry[1] >> 2) & 0x01);
                BMS_FAN_States[11] = (byte)((arry[1] >> 3) & 0x01);
                BMS_FAN_States[12] = (byte)((arry[1] >> 4) & 0x01);
                BMS_FAN_States[13] = (byte)((arry[1] >> 5) & 0x01);
                BMS_FAN_States[14] = (byte)((arry[1] >> 6) & 0x01);
                BMS_FAN_States[15] = (byte)((arry[1] >> 7) & 0x01);

                BMS_FAN_States[16] = (byte)((arry[2] >> 0) & 0x01);
                BMS_FAN_States[17] = (byte)((arry[2] >> 1) & 0x01);
                BMS_FAN_States[18] = (byte)((arry[2] >> 2) & 0x01);
                BMS_FAN_States[19] = (byte)((arry[2] >> 3) & 0x01);
                BMS_FAN_States[20] = (byte)((arry[2] >> 4) & 0x01);
                BMS_FAN_States[21] = (byte)((arry[2] >> 5) & 0x01);
                BMS_FAN_States[22] = (byte)((arry[2] >> 6) & 0x01);
                BMS_FAN_States[23] = (byte)((arry[2] >> 7) & 0x01);

                BMS_FAN_States[24] = (byte)((arry[3] >> 0) & 0x01);
                BMS_FAN_States[25] = (byte)((arry[3] >> 1) & 0x01);
                BMS_FAN_States[26] = (byte)((arry[3] >> 2) & 0x01);
                BMS_FAN_States[27] = (byte)((arry[3] >> 3) & 0x01);
                BMS_FAN_States[28] = (byte)((arry[3] >> 4) & 0x01);
                BMS_FAN_States[29] = (byte)((arry[3] >> 5) & 0x01);
                BMS_FAN_States[30] = (byte)((arry[3] >> 6) & 0x01);
                BMS_FAN_States[31] = (byte)((arry[3] >> 7) & 0x01);
            }
            if ((uint)MyDefine.DBC_ID.BMS_ID == id)
            {
                DBCData.BMS_ID = arry[0];
                DBCData.BMS_SOE = (ushort)(arry[1] << 8 | arry[2]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_ClusterType_DiffAvg == id)
            {
                DBCData.BMS_ClusterTemp_type = (byte)(arry[0]-1);
                DBCData.BMS_CellDiffTemp = (ushort)(arry[1] << 8 | arry[2]);
                DBCData.BMS_CellAvgTemp = (ushort)(arry[3] << 8 | arry[4]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_CluTempMaxMin1 == id)
            {
                DBCData.BMS_CellMaxTemp1 = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_CellNumMaxTemp1 = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_CellMinTemp1 = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_CellNumMinTemp1 = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_CluTempMaxMin2 == id)
            {
                DBCData.BMS_CellMaxTemp2 = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_CellNumMaxTemp2 = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_CellMinTemp2 = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_CellNumMinTemp2 = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_CluTempMaxMin3 == id)
            {
                DBCData.BMS_CellMaxTemp3 = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_CellNumMaxTemp3 = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_CellMinTemp3 = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_CellNumMinTemp3 = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_Read_Type == id)
            {
                DBCData.BMS_Read_Type = arry[0];
            }
            if ((uint)MyDefine.DBC_ID.BMS_Time == id)
            {
                DBCData.BMS_StartTime_Year = (byte)(arry[0] >> 2);
                DBCData.BMS_StartTime_Day = (byte)(arry[0] & 0x03 << 3 | arry[1] >> 5);
                DBCData.BMS_StartTime_Month = (byte)(arry[1] & 0x1F >> 1);
                DBCData.BMS_StartTime_Hour = (byte)(arry[1] & 0x01 << 4 | arry[2] >> 4);
                DBCData.BMS_StartTime_Minute = (byte)(arry[2] & 0x0F << 2 | arry[3] >> 6);
                DBCData.BMS_StartTime_Second = (byte)(arry[3] & 0x3F);
                DBCData.BMS_EndTime_Year = (byte)(arry[4] >> 2);
                DBCData.BMS_EndTime_Day = (byte)(arry[4] & 0x03 << 3 | arry[5] >> 5);
                DBCData.BMS_EndTime_Month = (byte)(arry[5] & 0x1F >> 1);
                DBCData.BMS_EndTime_Hour = (byte)(arry[5] & 0x01 << 4 | arry[6] >> 4);
                DBCData.BMS_EndTime_Minute = (byte)(arry[6] & 0x0F << 2 | arry[7] >> 6);
                DBCData.BMS_EndTime_Second = (byte)(arry[7] & 0x3F);
            }
            if ((uint)MyDefine.DBC_ID.BMS_SingleCap_Erg == id)
            {
                DBCData.BMS_SingleChgCapacity = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_SingleDchgCapacity = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_SingleChgEnergy = (ushort)(arry[4] << 8 | arry[5]);
                DBCData.BMS_SingleDchgEnergy = (ushort)(arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_TotalCapacity == id)
            {
                DBCData.BMS_TotalChgCapacity = (UInt32)(arry[0] << 24 | arry[1] << 16 | arry[2] << 8 | arry[3]);
                DBCData.BMS_TotalDchgCapacity = (UInt32)(arry[4] << 24 | arry[5] << 16 | arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.BMS_TotalEnergy == id)
            {
                DBCData.BMS_TotalChgEnergy = (UInt32)(arry[0] << 24 | arry[1] << 16 | arry[2] << 8 | arry[3]);
                DBCData.BMS_TotalDchgEnergy = (UInt32)(arry[4] << 24 | arry[5] << 16 | arry[6] << 8 | arry[7]);
            }
            if ((uint)MyDefine.DBC_ID.CAB500_CAN_3C2 == id)
            {
                DBCData.IP_VALUE_CAB_CAN = (UInt32)(arry[0] << 24 | arry[1] << 16 | arry[2] << 8 | arry[3]);
            }
            if ((uint)MyDefine.DBC_ID.Test_BMS_BSWDebugFr == id)
            {
                DBCData.Test_BMS_BSWDebugFr = arry[0];
            }
            if ((uint)MyDefine.DBC_ID.XCP_Tx == id)
            {
                DBCData.ID_CFG_BMS_Res = arry[0];
                DBCData.ID_CFG_EMS_Res = arry[1];
                DBCData.PreDV_Res = arry[2];
                DBCData.PowerupCmd_Res = arry[3];
                DBCData.AFE_Num_Res = arry[4];
            }
            if ((uint)MyDefine.DBC_ID.XCP_Rx == id)
            {
                DBCData.ID_CFG_BMS = arry[0];
                DBCData.ID_CFG_EMS = arry[1];
                DBCData.PreDV = arry[2];
                DBCData.PowerupCmd = arry[3];
                DBCData.AFE_Num = arry[4];
            }
            if ((uint)MyDefine.DBC_ID.BMS_Calibration1 == id)
            {
                DBCData.BMS_Calib_DisSOC = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_Calib_TrueSOC = (ushort)(arry[2] << 8 | arry[3]);
                DBCData.BMS_Calib_SOE = (ushort)(arry[4] << 8 | arry[5]);
            }
            /*
            博最dbc 均衡状态
            if ((uint)MyDefine.DBC_ID.DV_BMS_Cell_BALA_FB == id)
            {//DV_BMS_Cell_BALA_FB   
                DBCData.DV_BMS_Balane_Page = arry[0];//1页 54个状态,共8个板,8个页
                DV_BMS_Cell_BALA_FB[0 + 64 * cellpagenumber] = (byte)((arry[1] >> 0) & 0x01);
                DV_BMS_Cell_BALA_FB[1 + 64 * cellpagenumber] = (byte)((arry[1] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[2 + 64 * cellpagenumber] = (byte)((arry[1] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[3 + 64 * cellpagenumber] = (byte)((arry[1] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[4 + 64 * cellpagenumber] = (byte)((arry[1] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[5 + 64 * cellpagenumber] = (byte)((arry[1] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[6 + 64 * cellpagenumber] = (byte)((arry[1] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[7 + 64 * cellpagenumber] = (byte)((arry[1] >> 7) & 0x01);

                DV_BMS_Cell_BALA_FB[8 + 64 * cellpagenumber] = (byte)((arry[2] >> 0) & 0x01);
                DV_BMS_Cell_BALA_FB[9 + 64 * cellpagenumber] = (byte)((arry[2] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[10 + 64 * cellpagenumber] = (byte)((arry[2] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[11 + 64 * cellpagenumber] = (byte)((arry[2] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[12 + 64 * cellpagenumber] = (byte)((arry[2] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[13 + 64 * cellpagenumber] = (byte)((arry[2] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[14 + 64 * cellpagenumber] = (byte)((arry[2] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[15 + 64 * cellpagenumber] = (byte)((arry[2] >> 7) & 0x01);

                DV_BMS_Cell_BALA_FB[16 + 64 * cellpagenumber] = (byte)((arry[3] >> 0) & 0x01);
                DV_BMS_Cell_BALA_FB[17 + 64 * cellpagenumber] = (byte)((arry[3] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[18 + 64 * cellpagenumber] = (byte)((arry[3] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[19 + 64 * cellpagenumber] = (byte)((arry[3] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[20 + 64 * cellpagenumber] = (byte)((arry[3] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[21 + 64 * cellpagenumber] = (byte)((arry[3] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[22 + 64 * cellpagenumber] = (byte)((arry[3] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[23 + 64 * cellpagenumber] = (byte)((arry[3] >> 7) & 0x01);

                DV_BMS_Cell_BALA_FB[24 + 64 * cellpagenumber] = (byte)((arry[4] >> 0) & 0x01);
                DV_BMS_Cell_BALA_FB[25 + 64 * cellpagenumber] = (byte)((arry[4] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[26 + 64 * cellpagenumber] = (byte)((arry[4] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[27 + 64 * cellpagenumber] = (byte)((arry[4] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[28 + 64 * cellpagenumber] = (byte)((arry[4] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[29 + 64 * cellpagenumber] = (byte)((arry[4] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[30 + 64 * cellpagenumber] = (byte)((arry[4] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[31 + 64 * cellpagenumber] = (byte)((arry[4] >> 7) & 0x01);

                DV_BMS_Cell_BALA_FB[32 + 64 * cellpagenumber] = (byte)((arry[5] >> 0) & 0x01);
                DV_BMS_Cell_BALA_FB[33 + 64 * cellpagenumber] = (byte)((arry[5] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[34 + 64 * cellpagenumber] = (byte)((arry[5] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[35 + 64 * cellpagenumber] = (byte)((arry[5] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[36 + 64 * cellpagenumber] = (byte)((arry[5] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[37 + 64 * cellpagenumber] = (byte)((arry[5] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[38 + 64 * cellpagenumber] = (byte)((arry[5] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[39 + 64 * cellpagenumber] = (byte)((arry[5] >> 7) & 0x01);

                DV_BMS_Cell_BALA_FB[40 + 64 * cellpagenumber] = (byte)((arry[6] >> 0) & 0x01);
                DV_BMS_Cell_BALA_FB[41 + 64 * cellpagenumber] = (byte)((arry[6] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[42 + 64 * cellpagenumber] = (byte)((arry[6] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[43 + 64 * cellpagenumber] = (byte)((arry[6] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[44 + 64 * cellpagenumber] = (byte)((arry[6] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[45 + 64 * cellpagenumber] = (byte)((arry[6] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[46 + 64 * cellpagenumber] = (byte)((arry[6] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[47 + 64 * cellpagenumber] = (byte)((arry[6] >> 7) & 0x01);

                DV_BMS_Cell_BALA_FB[48 + 64 * cellpagenumber] = (byte)((arry[7] >> 0) & 0x01);
                DV_BMS_Cell_BALA_FB[49 + 64 * cellpagenumber] = (byte)((arry[7] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[50 + 64 * cellpagenumber] = (byte)((arry[7] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[51 + 64 * cellpagenumber] = (byte)((arry[7] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[52 + 64 * cellpagenumber] = (byte)((arry[7] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[53 + 64 * cellpagenumber] = (byte)((arry[7] >> 5) & 0x01);
            }
            * 博最dbc 均衡开关
            if ((uint)MyDefine.DBC_ID.DV_EOL_BALA_COMM == id)
            {//DV_EOL_BALA_COMM
                DBCData.DV_BMS_Balane_Page = arry[0];
                DV_EOL_BALA_COMM[0 + 64 * cellpagenumber] = (byte)((arry[1] >> 0) & 0x01);
                DV_EOL_BALA_COMM[1 + 64 * cellpagenumber] = (byte)((arry[1] >> 1) & 0x01);
                DV_EOL_BALA_COMM[2 + 64 * cellpagenumber] = (byte)((arry[1] >> 2) & 0x01);
                DV_EOL_BALA_COMM[3 + 64 * cellpagenumber] = (byte)((arry[1] >> 3) & 0x01);
                DV_EOL_BALA_COMM[4 + 64 * cellpagenumber] = (byte)((arry[1] >> 4) & 0x01);
                DV_EOL_BALA_COMM[5 + 64 * cellpagenumber] = (byte)((arry[1] >> 5) & 0x01);
                DV_EOL_BALA_COMM[6 + 64 * cellpagenumber] = (byte)((arry[1] >> 6) & 0x01);
                DV_EOL_BALA_COMM[7 + 64 * cellpagenumber] = (byte)((arry[1] >> 7) & 0x01);

                DV_EOL_BALA_COMM[8 + 64 * cellpagenumber] = (byte)((arry[2] >> 0) & 0x01);
                DV_EOL_BALA_COMM[9 + 64 * cellpagenumber] = (byte)((arry[2] >> 1) & 0x01);
                DV_EOL_BALA_COMM[10 + 64 * cellpagenumber] = (byte)((arry[2] >> 2) & 0x01);
                DV_EOL_BALA_COMM[11 + 64 * cellpagenumber] = (byte)((arry[2] >> 3) & 0x01);
                DV_EOL_BALA_COMM[12 + 64 * cellpagenumber] = (byte)((arry[2] >> 4) & 0x01);
                DV_EOL_BALA_COMM[13 + 64 * cellpagenumber] = (byte)((arry[2] >> 5) & 0x01);
                DV_EOL_BALA_COMM[14 + 64 * cellpagenumber] = (byte)((arry[2] >> 6) & 0x01);
                DV_EOL_BALA_COMM[15 + 64 * cellpagenumber] = (byte)((arry[2] >> 7) & 0x01);

                DV_EOL_BALA_COMM[16 + 64 * cellpagenumber] = (byte)((arry[3] >> 0) & 0x01);
                DV_EOL_BALA_COMM[17 + 64 * cellpagenumber] = (byte)((arry[3] >> 1) & 0x01);
                DV_EOL_BALA_COMM[18 + 64 * cellpagenumber] = (byte)((arry[3] >> 2) & 0x01);
                DV_EOL_BALA_COMM[19 + 64 * cellpagenumber] = (byte)((arry[3] >> 3) & 0x01);
                DV_EOL_BALA_COMM[20 + 64 * cellpagenumber] = (byte)((arry[3] >> 4) & 0x01);
                DV_EOL_BALA_COMM[21 + 64 * cellpagenumber] = (byte)((arry[3] >> 5) & 0x01);
                DV_EOL_BALA_COMM[22 + 64 * cellpagenumber] = (byte)((arry[3] >> 6) & 0x01);
                DV_EOL_BALA_COMM[23 + 64 * cellpagenumber] = (byte)((arry[3] >> 7) & 0x01);

                DV_EOL_BALA_COMM[24 + 64 * cellpagenumber] = (byte)((arry[4] >> 0) & 0x01);
                DV_EOL_BALA_COMM[25 + 64 * cellpagenumber] = (byte)((arry[4] >> 1) & 0x01);
                DV_EOL_BALA_COMM[26 + 64 * cellpagenumber] = (byte)((arry[4] >> 2) & 0x01);
                DV_EOL_BALA_COMM[27 + 64 * cellpagenumber] = (byte)((arry[4] >> 3) & 0x01);
                DV_EOL_BALA_COMM[28 + 64 * cellpagenumber] = (byte)((arry[4] >> 4) & 0x01);
                DV_EOL_BALA_COMM[29 + 64 * cellpagenumber] = (byte)((arry[4] >> 5) & 0x01);
                DV_EOL_BALA_COMM[30 + 64 * cellpagenumber] = (byte)((arry[4] >> 6) & 0x01);
                DV_EOL_BALA_COMM[31 + 64 * cellpagenumber] = (byte)((arry[4] >> 7) & 0x01);

                DV_EOL_BALA_COMM[32 + 64 * cellpagenumber] = (byte)((arry[5] >> 0) & 0x01);
                DV_EOL_BALA_COMM[33 + 64 * cellpagenumber] = (byte)((arry[5] >> 1) & 0x01);
                DV_EOL_BALA_COMM[34 + 64 * cellpagenumber] = (byte)((arry[5] >> 2) & 0x01);
                DV_EOL_BALA_COMM[35 + 64 * cellpagenumber] = (byte)((arry[5] >> 3) & 0x01);
                DV_EOL_BALA_COMM[36 + 64 * cellpagenumber] = (byte)((arry[5] >> 4) & 0x01);
                DV_EOL_BALA_COMM[37 + 64 * cellpagenumber] = (byte)((arry[5] >> 5) & 0x01);
                DV_EOL_BALA_COMM[38 + 64 * cellpagenumber] = (byte)((arry[5] >> 6) & 0x01);
                DV_EOL_BALA_COMM[39 + 64 * cellpagenumber] = (byte)((arry[5] >> 7) & 0x01);

                DV_EOL_BALA_COMM[40 + 64 * cellpagenumber] = (byte)((arry[6] >> 0) & 0x01);
                DV_EOL_BALA_COMM[41 + 64 * cellpagenumber] = (byte)((arry[6] >> 1) & 0x01);
                DV_EOL_BALA_COMM[42 + 64 * cellpagenumber] = (byte)((arry[6] >> 2) & 0x01);
                DV_EOL_BALA_COMM[43 + 64 * cellpagenumber] = (byte)((arry[6] >> 3) & 0x01);
                DV_EOL_BALA_COMM[44 + 64 * cellpagenumber] = (byte)((arry[6] >> 4) & 0x01);
                DV_EOL_BALA_COMM[45 + 64 * cellpagenumber] = (byte)((arry[6] >> 5) & 0x01);
                DV_EOL_BALA_COMM[46 + 64 * cellpagenumber] = (byte)((arry[6] >> 6) & 0x01);
                DV_EOL_BALA_COMM[47 + 64 * cellpagenumber] = (byte)((arry[6] >> 7) & 0x01);

                DV_EOL_BALA_COMM[48 + 64 * cellpagenumber] = (byte)((arry[7] >> 0) & 0x01);
                DV_EOL_BALA_COMM[49 + 64 * cellpagenumber] = (byte)((arry[7] >> 1) & 0x01);
                DV_EOL_BALA_COMM[50 + 64 * cellpagenumber] = (byte)((arry[7] >> 2) & 0x01);
                DV_EOL_BALA_COMM[51 + 64 * cellpagenumber] = (byte)((arry[7] >> 3) & 0x01);
                DV_EOL_BALA_COMM[52 + 64 * cellpagenumber] = (byte)((arry[7] >> 4) & 0x01);
                DV_EOL_BALA_COMM[53 + 64 * cellpagenumber] = (byte)((arry[7] >> 5) & 0x01);
            }
            // * 博最dbc 单体电压
            if ((uint)MyDefine.DBC_ID.BMS_CellVolt027_Avg == id)
            {
                DBCData.BMS_CellVolt_type =(ushort) (arry[2]-1);
                BMS_CellVolt[104 + DBCData.BMS_CellVolt_type * 105] = (ushort)(arry[0] << 8 | arry[1]);
                DBCData.BMS_AvgVolt = (ushort)(arry[3] << 8 | arry[4]);
            }
            if (id >= (uint)MyDefine.DBC_ID.BMS_CellVolt001 && id <= (uint)MyDefine.DBC_ID.BMS_CellVolt026)
            {
                BMS_CellVolt[(0 + 4 * (id - (uint)MyDefine.DBC_ID.BMS_CellVolt001)) + DBCData.BMS_CellVolt_type  * 105] = (ushort)(arry[0] << 8 | arry[1]);
                BMS_CellVolt[(1 + 4 * (id - (uint)MyDefine.DBC_ID.BMS_CellVolt001)) + DBCData.BMS_CellVolt_type  * 105] = (ushort)(arry[2] << 8 | arry[3]);
                BMS_CellVolt[(2 + 4 * (id - (uint)MyDefine.DBC_ID.BMS_CellVolt001)) + DBCData.BMS_CellVolt_type  * 105] = (ushort)(arry[4] << 8 | arry[5]);
                BMS_CellVolt[(3 + 4 * (id - (uint)MyDefine.DBC_ID.BMS_CellVolt001)) + DBCData.BMS_CellVolt_type  * 105] = (ushort)(arry[6] << 8 | arry[7]);
            }
            // * 博最dbc 单体温度
            if (id >= (uint)MyDefine.DBC_ID.BMS_ClusterTemp01 && id <= (uint)MyDefine.DBC_ID.BMS_ClusterTemp15)
            {
                Array.Copy(arry, 0, BMS_ClusterTemp, (DBCData.BMS_ClusterTemp_type * 120) + 8 * (id - (uint)MyDefine.DBC_ID.BMS_ClusterTemp01), 8);
            }
            */
            //单体电压 
            if ((id >= (uint)MyDefine.DBC_ID.BMS_CELLVOLMIN && id < (uint)MyDefine.DBC_ID.BMS_CELLVOLMIN+128))
            {
                cellinfocanouttime = 50;
                uint cellpagenumber = id - (uint)MyDefine.DBC_ID.BMS_CELLVOLMIN;
                BMS_CellVolt[0 + 4 * cellpagenumber] = (ushort)(arry[0] << 8 | arry[1]);
                BMS_CellVolt[1 + 4 * cellpagenumber] = (ushort)(arry[2] << 8 | arry[3]);
                BMS_CellVolt[2 + 4 * cellpagenumber] = (ushort)(arry[4] << 8 | arry[5]);
                BMS_CellVolt[3 + 4 * cellpagenumber] = (ushort)(arry[6] << 8 | arry[7]);
            }
            //单体温度
            if ((id >= (uint)MyDefine.DBC_ID.BMS_CELLTEMPMIN && id < (uint)MyDefine.DBC_ID.BMS_CELLTEMPMIN + 64))
            {
                uint cellpagenumber = id - (uint)MyDefine.DBC_ID.BMS_CELLTEMPMIN;
                Array.Copy(arry, 0, BMS_ClusterTemp,8 * cellpagenumber, 8);
            }
            //单体均衡状态  
            if ((id == (uint)MyDefine.DBC_ID.BMS_CELLBALAMIN) && id < (uint)MyDefine.DBC_ID.BMS_CELLBALAMIN + 8)
            {
                uint cellpagenumber = id - (uint)MyDefine.DBC_ID.BMS_CELLBALAMIN;
                DV_BMS_Cell_BALA_FB[0 + 64 * cellpagenumber] = (byte)((arry[0] >> 7) & 0x01);
                DV_BMS_Cell_BALA_FB[1 + 64 * cellpagenumber] = (byte)((arry[0] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[2 + 64 * cellpagenumber] = (byte)((arry[0] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[3 + 64 * cellpagenumber] = (byte)((arry[0] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[4 + 64 * cellpagenumber] = (byte)((arry[0] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[5 + 64 * cellpagenumber] = (byte)((arry[0] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[6 + 64 * cellpagenumber] = (byte)((arry[0] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[7 + 64 * cellpagenumber] = (byte)((arry[0] >> 0) & 0x01);

                DV_BMS_Cell_BALA_FB[8 + 64 * cellpagenumber] = (byte)((arry[1] >> 7) & 0x01);
                DV_BMS_Cell_BALA_FB[9 + 64 * cellpagenumber] = (byte)((arry[1] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[10 + 64 * cellpagenumber] = (byte)((arry[1] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[11 + 64 * cellpagenumber] = (byte)((arry[1] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[12 + 64 * cellpagenumber] = (byte)((arry[1] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[13 + 64 * cellpagenumber] = (byte)((arry[1] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[14 + 64 * cellpagenumber] = (byte)((arry[1] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[15 + 64 * cellpagenumber] = (byte)((arry[1] >> 0) & 0x01);

                DV_BMS_Cell_BALA_FB[16 + 64 * cellpagenumber] = (byte)((arry[2] >> 7) & 0x01);
                DV_BMS_Cell_BALA_FB[17 + 64 * cellpagenumber] = (byte)((arry[2] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[18 + 64 * cellpagenumber] = (byte)((arry[2] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[19 + 64 * cellpagenumber] = (byte)((arry[2] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[20 + 64 * cellpagenumber] = (byte)((arry[2] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[21 + 64 * cellpagenumber] = (byte)((arry[2] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[22 + 64 * cellpagenumber] = (byte)((arry[2] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[23 + 64 * cellpagenumber] = (byte)((arry[2] >> 0) & 0x01);

                DV_BMS_Cell_BALA_FB[24 + 64 * cellpagenumber] = (byte)((arry[3] >> 7) & 0x01);
                DV_BMS_Cell_BALA_FB[25 + 64 * cellpagenumber] = (byte)((arry[3] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[26 + 64 * cellpagenumber] = (byte)((arry[3] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[27 + 64 * cellpagenumber] = (byte)((arry[3] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[28 + 64 * cellpagenumber] = (byte)((arry[3] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[29 + 64 * cellpagenumber] = (byte)((arry[3] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[30 + 64 * cellpagenumber] = (byte)((arry[3] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[31 + 64 * cellpagenumber] = (byte)((arry[3] >> 0) & 0x01);

                DV_BMS_Cell_BALA_FB[32 + 64 * cellpagenumber] = (byte)((arry[4] >> 7) & 0x01);
                DV_BMS_Cell_BALA_FB[33 + 64 * cellpagenumber] = (byte)((arry[4] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[34 + 64 * cellpagenumber] = (byte)((arry[4] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[35 + 64 * cellpagenumber] = (byte)((arry[4] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[36 + 64 * cellpagenumber] = (byte)((arry[4] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[37 + 64 * cellpagenumber] = (byte)((arry[4] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[38 + 64 * cellpagenumber] = (byte)((arry[4] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[39 + 64 * cellpagenumber] = (byte)((arry[4] >> 0) & 0x01);

                DV_BMS_Cell_BALA_FB[40 + 64 * cellpagenumber] = (byte)((arry[5] >> 7) & 0x01);
                DV_BMS_Cell_BALA_FB[41 + 64 * cellpagenumber] = (byte)((arry[5] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[42 + 64 * cellpagenumber] = (byte)((arry[5] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[43 + 64 * cellpagenumber] = (byte)((arry[5] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[44 + 64 * cellpagenumber] = (byte)((arry[5] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[45 + 64 * cellpagenumber] = (byte)((arry[5] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[46 + 64 * cellpagenumber] = (byte)((arry[5] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[47 + 64 * cellpagenumber] = (byte)((arry[5] >> 0) & 0x01);

                DV_BMS_Cell_BALA_FB[48 + 64 * cellpagenumber] = (byte)((arry[6] >> 7) & 0x01);
                DV_BMS_Cell_BALA_FB[49 + 64 * cellpagenumber] = (byte)((arry[6] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[50 + 64 * cellpagenumber] = (byte)((arry[6] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[51 + 64 * cellpagenumber] = (byte)((arry[6] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[52 + 64 * cellpagenumber] = (byte)((arry[6] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[53 + 64 * cellpagenumber] = (byte)((arry[6] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[54 + 64 * cellpagenumber] = (byte)((arry[6] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[55 + 64 * cellpagenumber] = (byte)((arry[6] >> 0) & 0x01);

                DV_BMS_Cell_BALA_FB[56 + 64 * cellpagenumber] = (byte)((arry[7] >> 7) & 0x01);
                DV_BMS_Cell_BALA_FB[57 + 64 * cellpagenumber] = (byte)((arry[7] >> 6) & 0x01);
                DV_BMS_Cell_BALA_FB[58 + 64 * cellpagenumber] = (byte)((arry[7] >> 5) & 0x01);
                DV_BMS_Cell_BALA_FB[59 + 64 * cellpagenumber] = (byte)((arry[7] >> 4) & 0x01);
                DV_BMS_Cell_BALA_FB[60 + 64 * cellpagenumber] = (byte)((arry[7] >> 3) & 0x01);
                DV_BMS_Cell_BALA_FB[61 + 64 * cellpagenumber] = (byte)((arry[7] >> 2) & 0x01);
                DV_BMS_Cell_BALA_FB[62 + 64 * cellpagenumber] = (byte)((arry[7] >> 1) & 0x01);
                DV_BMS_Cell_BALA_FB[63 + 64 * cellpagenumber] = (byte)((arry[7] >> 0) & 0x01);
            }
            //国标预警信息
            if ((uint)MyDefine.DBC_ID.BMS_GBWARNINGINFO1 == id)
            {
                Array.Copy(arry, 0, BMS_GB_FaultInfomation, 0, 8);//64
            }
            if ((uint)MyDefine.DBC_ID.BMS_GBWARNINGINFO2 == id)
            {
                Array.Copy(arry, 0, BMS_GB_FaultInfomation, 8, 2);//16
            }
            //
            if ((id >= (uint)MyDefine.DBC_ID.BMS_PCB_Temp1 && id <= (uint)MyDefine.DBC_ID.BMS_PCB_Temp7) )
            {
                Array.Copy(arry, 0, BMS_CSC_PCB_Temp, 8 * (id - (uint)MyDefine.DBC_ID.BMS_PCB_Temp1), 8);
            }
            if ((uint)MyDefine.DBC_ID.BMS_PCB_Temp8 == id)
            {
                Array.Copy(arry, 0, BMS_CSC_PCB_Temp, 56, 8);
            }
            if (id >= (uint)MyDefine.DBC_ID.BMS_AFE_Temp1 && id <= (uint)MyDefine.DBC_ID.BMS_AFE_Temp8)
            {
                Array.Copy(arry, 0, BMS_AFETemp, 8 * (id - (uint)MyDefine.DBC_ID.BMS_AFE_Temp1), 8);
            }

            if (id >= (uint)MyDefine.DBC_ID.BMS_AFEVolt01 && id <= (uint)MyDefine.DBC_ID.BMS_AFEVolt08)
            {
                BMS_AFEVolt[(0 + 4 * (id - (uint)MyDefine.DBC_ID.BMS_AFEVolt01))] = (ushort)(arry[0] << 8 | arry[1]);
                BMS_AFEVolt[(1 + 4 * (id - (uint)MyDefine.DBC_ID.BMS_AFEVolt01))] = (ushort)(arry[2] << 8 | arry[3]);
                BMS_AFEVolt[(2 + 4 * (id - (uint)MyDefine.DBC_ID.BMS_AFEVolt01))] = (ushort)(arry[4] << 8 | arry[5]);
                BMS_AFEVolt[(3 + 4 * (id - (uint)MyDefine.DBC_ID.BMS_AFEVolt01))] = (ushort)(arry[6] << 8 | arry[7]);
            }
        }
        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            ControlPaint.DrawBorder(e.Graphics, panel24.ClientRectangle, Color.Black, ButtonBorderStyle.Solid);
        }
        private void button6_Click(object sender, EventArgs e)
        {
            if (m_bOpen == 0)
                return;
            if (canMessage_stop == 0)
            {
                canMessage_stop = 1;
                button6.Text = "显示";
            }
            else
            {
                canMessage_stop = 0;
                button6.Text = "不显";
            }
        }
        private System.Windows.Forms.UserControl control;

 
        public void WriteControl_SOX()
        {
            SetSOHValue = 96;
            SetSOCValue = 20;
            SetSOEValue = 96;
            if (SetSOHValue > userProcessBatSOH.Value)
            {
                userProcessBatSOH.Value++;
            }
            if (SetSOHValue < userProcessBatSOH.Value)
            {
                userProcessBatSOH.Value--;
            }
            if (SetSOCValue > userProcessBatSOC.Value)
            {
                userProcessBatSOC.Value++;
            }
            if (SetSOCValue < userProcessBatSOC.Value)
            {
                userProcessBatSOC.Value--;
            }
            if (SetSOEValue > userProcessBatSOE.Value)
            {
                userProcessBatSOE.Value++;
            }
            if (SetSOEValue < userProcessBatSOE.Value)
            {
                userProcessBatSOE.Value--;
            }

        }
        void WriteTabControlMain_Page1()
        {
            //
            /*
            DBCData.BMS_CellVoltMax1 = 3610;
            DBCData.BMS_CellVoltMax2 = 3660;
            DBCData.BMS_CellVoltMax3 = 3690;
            DBCData.BMS_NumberCellVoltMax1 = 320;
            DBCData.BMS_NumberCellVoltMax2 = 333;
            DBCData.BMS_NumberCellVoltMax3 = 354;
            DBCData.BMS_SOH = 900;
            DBCData.BMS_SOC = 900;
            DBCData.BMS_BattVolt = 14280;
            DBCData.BMS_Cluster_Curr = 17890;
            DBCData.BMS_ShuntTemp_1 = 790;
            DBCData.BMS_SOE = 990;
            DBCData.BMS_CellVoltMin1 = 3510;
            DBCData.BMS_CellVoltMin2 = 3520;
            DBCData.BMS_CellVoltMin3 = 3530;
            DBCData.BMS_NumberCellVoltMin1 = 10;
            DBCData.BMS_NumberCellVoltMin2 = 22;
            DBCData.BMS_NumberCellVoltMin3 = 46;
            DBCData.BMS_CellMaxTemp1 = 81;
            DBCData.BMS_CellMaxTemp2 = 85;
            DBCData.BMS_CellMaxTemp3 = 88;
            DBCData.BMS_CellNumMaxTemp1 = 315;
            DBCData.BMS_CellNumMaxTemp2 = 352;
            DBCData.BMS_CellNumMaxTemp3 = 344;
            DBCData.BMS_CellMinTemp1 = 63;
            DBCData.BMS_CellMinTemp2 = 65;
            DBCData.BMS_CellMinTemp3 = 68;
            DBCData.BMS_CellNumMinTemp1 = 5;
            DBCData.BMS_CellNumMinTemp2 = 24;
            DBCData.BMS_CellNumMinTemp3 = 33;
            DBCData.BMS_EnvirTemp_1 = 73;
            DBCData.BMS_EnvirTemp_2 = 76;
            DBCData.BMS_EnvirTemp_3 = 87;
            DBCData.BMS_EnvirTemp_4 = 59;
            
            BMS_AFEVolt[0] = 455;
            BMS_AFEVolt[1] = 456;
            BMS_AFEVolt[2] = 458;
            BMS_AFEVolt[3] = 455;
            BMS_AFEVolt[4] = 455;
            BMS_AFEVolt[5] = 454;
            BMS_AFEVolt[6] = 455;
            BMS_AFEVolt[7] = 458;
            BMS_AFEVolt[8] = 455;
            BMS_AFEVolt[9] = 455;
            BMS_AFEVolt[10] = 455;
            BMS_AFEVolt[11] = 458;
            BMS_AFEVolt[12] = 455;
            BMS_AFEVolt[13] = 455;
            BMS_AFEVolt[14] = 454;
            BMS_AFEVolt[15] = 455; 
            BMS_AFEVolt[16] = 455;
            BMS_AFEVolt[17] = 456;
            BMS_AFEVolt[18] = 454;
            BMS_AFEVolt[19] = 455;
            BMS_AFEVolt[20] = 457;
            BMS_AFEVolt[21] = 455;
            BMS_AFEVolt[22] = 456;
            BMS_AFEVolt[23] = 455;
            BMS_AFEVolt[24] = 457;
            BMS_AFEVolt[25] = 455;
            BMS_AFEVolt[26] = 456;
            BMS_AFEVolt[27] = 455;
            BMS_AFEVolt[28] = 455;
            BMS_AFEVolt[29] = 458;
            BMS_AFEVolt[30] = 454;
            BMS_AFEVolt[31] = 455;

            DBCData.BMS_BattVolt = 14800;
            DBCData.BMS_Cluster_Curr = 16500;
            */
            SetSOHValue =(byte)( DBCData.BMS_SOH / 10);
            SetSOCValue =(byte)( DBCData.BMS_SOC / 10);        
            aGaugeVol.Value = DBCData.BMS_BattVolt / 10;
            aGaugeCur.Value = DBCData.BMS_Cluster_Curr * 0.1f - 1600;//簇电流

            WriteControl_SOX();

            textBox3.Text = (DBCData.BMS_CellVoltMax1 * 0.001).ToString();
            textBox11.Text = (DBCData.BMS_CellVoltMax2 * 0.001).ToString();
            textBox15.Text = (DBCData.BMS_CellVoltMax3 * 0.001).ToString();
            textBox8.Text = (DBCData.BMS_NumberCellVoltMax1 ).ToString();
            textBox12.Text = (DBCData.BMS_NumberCellVoltMax2).ToString();
            textBox16.Text = (DBCData.BMS_NumberCellVoltMax3).ToString();
            textBox9.Text = (DBCData.BMS_CellVoltMin1 * 0.001).ToString();
            textBox13.Text = (DBCData.BMS_CellVoltMin2 * 0.001).ToString();
            textBox17.Text = (DBCData.BMS_CellVoltMin3 * 0.001).ToString();
            textBox10.Text = (DBCData.BMS_NumberCellVoltMin1).ToString();
            textBox14.Text = (DBCData.BMS_NumberCellVoltMin2).ToString();
            textBox18.Text = (DBCData.BMS_NumberCellVoltMin3).ToString();
            textBox34.Text = (DBCData.BMS_CellMaxTemp1 - 40).ToString();
            textBox30.Text = (DBCData.BMS_CellMaxTemp2 - 40).ToString();
            textBox26.Text = (DBCData.BMS_CellMaxTemp3 - 40).ToString();
            textBox33.Text = (DBCData.BMS_CellNumMaxTemp1 ).ToString();
            textBox29.Text = (DBCData.BMS_CellNumMaxTemp2 ).ToString();
            textBox25.Text = (DBCData.BMS_CellNumMaxTemp3 ).ToString();
            textBox32.Text = (DBCData.BMS_CellMinTemp1 - 40).ToString();
            textBox28.Text = (DBCData.BMS_CellMinTemp2 - 40).ToString();
            textBox24.Text = (DBCData.BMS_CellMinTemp3 - 40).ToString();
            textBox31.Text = (DBCData.BMS_CellNumMinTemp1 ).ToString();
            textBox27.Text = (DBCData.BMS_CellNumMinTemp2 ).ToString();
            textBox23.Text = (DBCData.BMS_CellNumMinTemp3 ).ToString();
            textBox19.Text = (DBCData.BMS_IsolationR_Pos).ToString();
            textBox20.Text = (DBCData.BMS_IsolationR_Neg).ToString();
            textBox21.Text = DBCData.BMS_IsolationR.ToString();
            textBox22.Text = (DBCData.BMS_DTCNumber).ToString();
            textBox94.Text = (DBCData.BMS_EnvirTemp_1 - 40).ToString();
            textBox97.Text = (DBCData.BMS_EnvirTemp_2 - 40).ToString();
            textBox96.Text = (DBCData.BMS_EnvirTemp_3 - 40).ToString();
            textBox95.Text = (DBCData.BMS_EnvirTemp_4 - 40).ToString();
            textBox86.Text = (DBCData.BMS_ShuntTemp_1/10 - 40).ToString();//分流器电流
            textBox90.Text = DBCData.BMS_DI_HSD1Sts == 1 ? "闭合" : "断开"; //(DBCData.BMS_DI_HSD1Sts).ToString();
            textBox93.Text = DBCData.BMS_DI_HSD2Sts == 1 ? "闭合" : "断开"; //(DBCData.BMS_DI_HSD2Sts).ToString();
            textBox92.Text = DBCData.BMS_DI_HSD3Sts == 1 ? "闭合" : "断开"; //(DBCData.BMS_DI_HSD3Sts).ToString();
            textBox91.Text = "";
            textBox57.Text = DBCData.BMS_DI_LSD1Sts == 1 ? "闭合" : "断开";//(DBCData.BMS_DI_LSD1Sts).ToString();
            textBox85.Text = DBCData.BMS_DI_LSD2Sts == 1 ? "闭合" : "断开";//(DBCData.BMS_DI_LSD2Sts).ToString();
            textBox84.Text = DBCData.BMS_DI_LSD3Sts == 1 ? "闭合" : "断开";//(DBCData.BMS_DI_LSD3Sts).ToString();
            textBox83.Text = DBCData.BMS_DI_LSD4Sts == 1 ? "闭合" : "断开";//(DBCData.BMS_DI_LSD4Sts).ToString();
            textBox89.Text = (DBCData.BMS_BattSts).ToString();
            textBox88.Text = DBCData.BMS_PosRlyDriveCmd == 1 ? "闭合" : "断开";// (DBCData.BMS_PosRlyDriveCmd).ToString(); //主正
            textBox87.Text = DBCData.BMS_NegRlyDriveCmd == 1 ? "闭合" : "断开"; //(DBCData.BMS_NegRlyDriveCmd).ToString(); //主负
        }
        void WriteBMSAfeVolt()
        {
            for (byte i = 0; i < 32; i++)
            {
                 AfeVoltTbox[i].Text = (BMS_AFEVolt[i] *0.1).ToString();
            }
        }
        void WriteTabControlMain_Page2()
        {
            MainSlaveModeChange();

            WriteBMSCellInfo();

            WriteBMSPCBTemp();
            if (++Sys_time200mS_tick > 2)
            {
                Sys_time200mS_tick = 0;
                ChangeCellBatteryVolOrTempColor();
                ChangePCBTempColor();             
            }
            if (++Sys_time1S_tickPage2 > 10)
            {
                Sys_time1S_tickPage2 = 0;
                writebBMSCellnum();
            }
            WriteBMSAfeVolt();
        }
        public void FunGetFalutboxState(byte index, byte Eval, byte Enum, bool gbebox)
        {
            if (gbebox)
            {
                if (Falutinfo_gb[index] != null)
                {
                    if (((Eval >>(Enum)) & 0x01) == 1)
                    {
                        Falutinfo_gb[index].LevelBackColor = Color.Crimson;
                        Falutinfo_gb[index].CodeBackColor = Color.Crimson;
                        Falutinfo_gb[index].ForeColor = Color.White;
                        if (Falutinfo_gb[index].Type == 1)
                            groupBox7.ForeColor = Color.Crimson;
                        if (Falutinfo_gb[index].Type == 2)
                            groupBox10.ForeColor = Color.Crimson;
                        if (Falutinfo_gb[index].Type == 3)
                            groupBox9.ForeColor = Color.Crimson;
                    }
                    else
                    {
                        Falutinfo_gb[index].LevelBackColor = Color.White;
                        Falutinfo_gb[index].CodeBackColor = Color.White;
                        Falutinfo_gb[index].ForeColor = Color.Black;
                    }
                }
            }
            else
            {
                if (Falutinfo[index] != null)
                {
                    if (((Eval >> (Enum)) & 0x01) == 1)
                    {
                        Falutinfo[index].LevelBackColor = Color.Crimson;
                        Falutinfo[index].CodeBackColor = Color.Crimson;
                        Falutinfo[index].ForeColor = Color.White;
                        if (Falutinfo[index].Type == 1)
                            groupBox7.ForeColor = Color.Crimson;
                        if (Falutinfo[index].Type == 2)
                            groupBox10.ForeColor = Color.Crimson;
                        if (Falutinfo[index].Type == 3)
                            groupBox9.ForeColor = Color.Crimson;
                    }
                    else
                    {
                        Falutinfo[index].LevelBackColor = Color.White;
                        Falutinfo[index].CodeBackColor = Color.White;
                        Falutinfo[index].ForeColor = Color.Black;
                    }
                }
            }
            
        }
        void WriteTabControlMain_Page3()
        {
            //BMS_FaultInfomation[1] = 0x33;
            //BMS_GB_FaultInfomation[1] = 0x33;
            bool faultflag = false;
            if (++Sys_time1S_tickPage3 > 10)
            {
                Sys_time1S_tickPage3 = 0;   
            }
            if (syshasfalutmessage == true && Sys_time1S_tickPage3 < 5)
            {
                label6.BackColor = Color.Crimson;
                label6.ForeColor = Color.White;
            }
            else
            {
                label6.BackColor = Color.White;
                label6.ForeColor = Color.Black;
            }
            groupBox7.ForeColor = Color.ForestGreen;
            groupBox10.ForeColor = Color.ForestGreen;
            groupBox9.ForeColor = Color.ForestGreen;

            for (byte i = 0; i < BMS_FaultInfomation.Length; i++)
            {
                byte temp = 0, temp_gb = 0,J = 0;
                
                temp = BMS_FaultInfomation[i];
                if(i< BMS_GB_FaultInfomation.Length)
                    temp_gb = BMS_GB_FaultInfomation[i];               
                while (J < 8)
                {
                    byte Enumber_gb, Enumber;
                    if (i < BMS_GB_FaultInfomation.Length)
                    {
                        Enumber_gb = (byte)(i * 8 + J);
                        FunGetFalutboxState(Enumber_gb,temp_gb,J,true);
                    }
                    Enumber = (byte)(i * 8 + J);
                    FunGetFalutboxState(Enumber,temp,J,false);
                    J++;
                }
                if (temp_gb > 0 || temp > 0)
                {
                    faultflag = true;
                }
            }
            syshasfalutmessage = faultflag;
            WriteTabControlMain_ErrorLog();
        }
        void WriteTabControlMain_ErrorLog()
        {
            for(byte i = 0;i < BMS_FaultInfomation.Length; i++)
            {
                byte temp_gb = 0;
                if (i < BMS_GB_FaultInfomation.Length)
                {
                    temp_gb = (byte)(BMS_GB_FaultInfomation[i] ^ BMS_GB_FaultInfomation_LAST[i]);//同为0;异为1
                }
                byte temp = (byte)(BMS_FaultInfomation[i] ^ BMS_FaultInfomation_LAST[i]);
                if (temp_gb > 0|| temp >0)
                {
                    byte J = 0;
                    while(J<8)
                    {
                        if(((temp_gb >> J) & 0x01) == 1 && temp_gb > 0)
                        {
                            ErrorLogCnt++;
                            byte errornumber = (byte)(i * 8 + J);
                            int index = this.dataGridViewErr.Rows.Add();
                            dataGridViewErr.FirstDisplayedScrollingRowIndex = dataGridViewErr.RowCount - 1;
                            this.dataGridViewErr.Rows[index].Cells[0].Value = ErrorLogCnt;
                            this.dataGridViewErr.Rows[index].Cells[1].Value = System.DateTime.Now.ToString("G");
                            this.dataGridViewErr.Rows[index].Cells[2].Value = Falutinfo_gb[errornumber].LevelName + Falutinfo_gb[errornumber].InfoName;
                            if (((BMS_GB_FaultInfomation[i] >> J) & 0x01) == 1)
                                this.dataGridViewErr.Rows[index].Cells[3].Value = "出现";
                            else
                                this.dataGridViewErr.Rows[index].Cells[3].Value = "恢复";
                            this.dataGridViewErr.Rows[index].Cells[4].Value = "-";
                        }/*
                        if (((temp >> J) & 0x01) == 1 && temp > 0)
                        {
                            ErrorLogCnt++;
                            byte errornumber = (byte)(i * 8 + J);
                            int index = this.dataGridViewErr.Rows.Add();
                            dataGridViewErr.FirstDisplayedScrollingRowIndex = dataGridViewErr.RowCount - 1;
                            this.dataGridViewErr.Rows[index].Cells[0].Value = ErrorLogCnt;
                            this.dataGridViewErr.Rows[index].Cells[1].Value = System.DateTime.Now.ToString("G");
                            this.dataGridViewErr.Rows[index].Cells[2].Value = Falutinfo[errornumber].LevelName + Falutinfo[errornumber].InfoName;
                            if (((BMS_GB_FaultInfomation[i] >> J) & 0x01) == 1)
                                this.dataGridViewErr.Rows[index].Cells[3].Value = "出现";
                            else
                                this.dataGridViewErr.Rows[index].Cells[3].Value = "恢复";
                            this.dataGridViewErr.Rows[index].Cells[4].Value = "-";
                        }*/
                        J++;
                    }      
                }
            }
            Array.Copy(BMS_GB_FaultInfomation, 0, BMS_GB_FaultInfomation_LAST, 0, BMS_GB_FaultInfomation.Length);
            Array.Copy(BMS_FaultInfomation, 0, BMS_FaultInfomation_LAST, 0, BMS_FaultInfomation.Length);
        }
        /// <summary>
        /// 上位机与BMU通讯,超时未回复,
        /// </summary>
        void InSlaveModeOutTime()
        {
            if (Send_SlaveCheckcnt > 0)
            {
                if (Send_SlaveCheckcnt == 1)
                {
                    InSlaveCheck_updata = 1;//超时失败,更新
                }
                Send_SlaveCheckcnt--;
            }
            if (Send_SlaveAssignaddrcnt > 0)
            {
                if (Send_SlaveAssignaddrcnt == 1)
                {
                    InSlaveAssignaddr_updata = 1;//超时失败,更新
                }
                Send_SlaveAssignaddrcnt--;
            }
        }
        byte chartcnt = 0;
        
        private void timerSys_Tick(object sender, EventArgs e)
        {
            if(cellinfocanouttime > 0)
            {
                cellinfocanouttime--;
                if(cellinfocanouttime == 0)
                {
                    for (int i = 0; i < BMS_CellVolt.Length; i++)
                    {
                        if(BMS_CellVolt[i] > 0) BMS_CellVolt[i] = 5000;
                        BMS_ClusterTemp[i] = 0;
                        DV_BMS_Cell_BALA_FB[i] = 0;
                    }
                }
            }
            if(++chartcnt > 5)
            {

                //Send_FacInfoCheck();
                
                chartcnt = 0;
            }
            Send_InSlaveMode();
            InSlaveModeOutTime();

            WriteTabControlMain_Page1();
            WriteTabControlMain_Page2();
            WriteTabControlMain_Page3();
        }
        int MouseWheelCnt = 0;
        private void Panel1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            /*
            if (flowLayoutPanel1.VerticalScroll.Value + flowLayoutPanel1.Height > 1500) //滚动条在底部
                MouseWheelCnt++;
            if (flowLayoutPanel1.VerticalScroll.Value == 0)////滚动条在顶部
                MouseWheelCnt--;
            */
        }
        private void aGaugeVol_ValueChanged(object sender, EventArgs e)
        {
            aGaugelabelVol.Text = aGaugeVol.Value.ToString()+"V";
        }
        private void aGaugeCur_ValueChanged(object sender, EventArgs e)
        {
            aGaugelabelCur.Text = aGaugeCur.Value.ToString("0.0") + "A";
        }    

        private void cb_cellbalaEn_CheckedChanged(object sender, EventArgs e)
        {

            if ( cb_cellbalaEn.Checked == true)
            {
                bt_cellallclose.Enabled = true;
                bt_cellallopen.Enabled = true;
            }
            else
            {
                bt_cellallclose.Enabled = false;
                bt_cellallopen.Enabled = false;
            }
            for (byte i = 0;i < BMS_PAGECELLNUMBER_Max; i++) 
            {
               if (cb_cellbalaEn.Checked == true)
               {
                    if(i < BMS_BMUCellNum)
                    {                   
                        CellInfo[i].CellBALAEnable = true;
                    }
                    else
                    {
                        CellInfo[i].CellBALAEnable = false;
                    }
                }
                else
                {
                    CellInfo[i].CellBALAEnable = false;
                }

            }   
        }



        private void chart1_MouseEnter(object sender, EventArgs e)
        {
             LogWork.Text = "鼠标在折线图上";
            LogWork.ForeColor = Color.Black;
            MouseLocation = 2;
        }

        #region Delegates
        /// <summary>
        /// Read-Delegate Handler
        /// </summary>
        private delegate void ReadDelegateHandler();
        #endregion

        #region Members
        /// <summary>
        /// Saves the desired connection mode
        /// </summary>
        private bool m_IsFD;
        /// <summary>
        /// Saves the handle of a PCAN hardware
        /// </summary>
        private TPCANHandle m_PcanHandle;
        /// <summary>
        /// Saves the baudrate register for a conenction
        /// </summary>
        private TPCANBaudrate m_Baudrate;
        /// <summary>
        /// Saves the type of a non-plug-and-play hardware
        /// </summary>
        private TPCANType m_HwType;
        /// <summary>
        /// Stores the status of received messages for its display
        /// </summary>
        private System.Collections.ArrayList m_LastMsgsList;
        /// <summary>
        /// Read Delegate for calling the function "ReadMessages"
        /// </summary>
        private ReadDelegateHandler m_ReadDelegate;
        /// <summary>
        /// Receive-Event
        /// </summary>
        private System.Threading.AutoResetEvent m_ReceiveEvent;
        /// <summary>
        /// Thread for message reading (using events)
        /// </summary>
        private System.Threading.Thread m_ReadThread;
        /// <summary>
        /// Handles of non plug and play PCAN-Hardware
        /// </summary>
        private TPCANHandle[] m_NonPnPHandles;
        #endregion
        private string FormatChannelName(TPCANHandle handle)
        {
            return FormatChannelName(handle, false);
        }
        private string FormatChannelName(TPCANHandle handle, bool isFD)
        {
            TPCANDevice devDevice;
            byte byChannel;

            // Gets the owner device and channel for a 
            // PCAN-Basic handle
            //
            if (handle < 0x100)
            {
                devDevice = (TPCANDevice)(handle >> 4);
                byChannel = (byte)(handle & 0xF);
            }
            else
            {
                devDevice = (TPCANDevice)(handle >> 8);
                byChannel = (byte)(handle & 0xFF);
            }

            // Constructs the PCAN-Basic Channel name and return it
            //
            /*
            if (isFD)
                return string.Format("{0}:FD {1} ({2:X2}h)", devDevice, byChannel, handle);
            else
            */
                return string.Format("{0} {1} ({2:X2}h)", devDevice, byChannel, handle);
        }
        /// <summary>
        /// Activates/deaactivates the different controls of the main-form according
        /// with the current connection status
        /// </summary>
        /// <param name="bConnected">Current status. True if connected, false otherwise</param>
        private void SetConnectionStatus(bool bConnected)
        {
            /*
            if (!bConnected)
                cbbChannel_SelectedIndexChanged(this, new EventArgs());
            else
                rdbTimer_CheckedChanged(this, new EventArgs());
            */
        }
        /// <summary>
        /// Configures the PCAN-Trace file for a PCAN-Basic Channel
        /// </summary>
        private void ConfigureTraceFile()
        {
            UInt32 iBuffer;
            TPCANStatus stsResult;

            // Configure the maximum size of a trace file to 5 megabytes
            //
            iBuffer = 5;
            stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_TRACE_SIZE, ref iBuffer, sizeof(UInt32));
            if (stsResult != TPCANStatus.PCAN_ERROR_OK)
                LogWork.Text = GetFormatedError(stsResult);

            // Configure the way how trace files are created: 
            // * Standard name is used
            // * Existing file is ovewritten, 
            // * Only one file is created.
            // * Recording stopts when the file size reaches 5 megabytes.
            
            iBuffer = PCANBasic.TRACE_FILE_SINGLE | PCANBasic.TRACE_FILE_OVERWRITE;
            stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_TRACE_CONFIGURE, ref iBuffer, sizeof(UInt32));
            if (stsResult != TPCANStatus.PCAN_ERROR_OK)
                LogWork.Text = GetFormatedError(stsResult);
            else
                LogWork.Text = "连接成功 !";
        }
        private string GetFormatedError(TPCANStatus error)
        {
            StringBuilder strTemp;

            // Creates a buffer big enough for a error-text
            //
            strTemp = new StringBuilder(256);
            // Gets the text using the GetErrorText API function
            // If the function success, the translated error is returned. If it fails,
            // a text describing the current error is returned.
            //
            if (PCANBasic.GetErrorText(error, 0, strTemp) != TPCANStatus.PCAN_ERROR_OK)
                return string.Format("An error occurred. Error-code's text (0x{0:X}) couldn't be retrieved", error);
            else
                return strTemp.ToString();
        }
        
         uint PCAN_Connect()
        {
            UInt16 cbbIO = 0x100;
            UInt16 cbbInterrupt = 3;
            TPCANStatus stsResult;
            /*
            m_HwType = TPCANType.PCAN_TYPE_ISA;  "ISA-82C200",
            m_HwType = TPCANType.PCAN_TYPE_ISA_SJA;"ISA-SJA1000",          
            m_HwType = TPCANType.PCAN_TYPE_ISA_PHYTEC; "ISA-PHYTEC",              
            m_HwType = TPCANType.PCAN_TYPE_DNG;  "DNG-82C200",      
            m_HwType = TPCANType.PCAN_TYPE_DNG_EPP;  "DNG-82C200 EPP",
            m_HwType = TPCANType.PCAN_TYPE_DNG_SJA;   "DNG-SJA1000",
            m_HwType = TPCANType.PCAN_TYPE_DNG_SJA_EPP;  "DNG-SJA1000 EPP"
            */
            m_HwType = TPCANType.PCAN_TYPE_ISA;
            stsResult = PCANBasic.Initialize(
                    m_PcanHandle,
                    m_Baudrate,
                    m_HwType,
                    cbbIO,
                    cbbInterrupt);

            if (stsResult != TPCANStatus.PCAN_ERROR_OK)
                if (stsResult != TPCANStatus.PCAN_ERROR_CAUTION)
                    LogWork.Text = GetFormatedError(stsResult);
                else
                {
                    stsResult = TPCANStatus.PCAN_ERROR_OK;
                }
            else
                // Prepares the PCAN-Basic's PCAN-Trace file
                ConfigureTraceFile();

            SetConnectionStatus(stsResult == TPCANStatus.PCAN_ERROR_OK);
            if (stsResult == TPCANStatus.PCAN_ERROR_OK) return 1;
            else
            {
                return 0;
            }
        }

        private void comboBox_canbaud_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBox_canbaud.SelectedIndex)
            {
                case 8:
                    m_Baudrate = TPCANBaudrate.PCAN_BAUD_83K;
                    break;
                case 7:
                    m_Baudrate = TPCANBaudrate.PCAN_BAUD_33K;
                    break;
                case 6:
                    m_Baudrate = TPCANBaudrate.PCAN_BAUD_1M;
                    break;
                case 5:
                    m_Baudrate = TPCANBaudrate.PCAN_BAUD_800K;
                    break;
                case 4:
                    m_Baudrate = TPCANBaudrate.PCAN_BAUD_500K;
                    break;
                case 3:
                    m_Baudrate = TPCANBaudrate.PCAN_BAUD_250K;
                    break;
                case 2:
                    m_Baudrate = TPCANBaudrate.PCAN_BAUD_125K;
                    break;
                case 1:
                    m_Baudrate = TPCANBaudrate.PCAN_BAUD_50K;
                    break;
                case 0:
                    m_Baudrate = TPCANBaudrate.PCAN_BAUD_20K;
                    break;
            }
        }

        private void comboBox_devtype_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strTemp = comboBox_devtype.Text;
            if (strTemp.Contains("ZLG"))//周立功CAN盒
            {
                candevtype = 2;
                m_devtype  = (uint)comboBox_devtype.SelectedIndex;

            }
            else if(strTemp.Contains("PCAN"))
            {
                candevtype = 1;
                strTemp = strTemp.Substring(strTemp.IndexOf('(') + 1, 3);
                strTemp = strTemp.Replace('h', ' ').Trim(' ');
                // Determines if the handle belong to a No Plug&Play hardware 
                m_PcanHandle = Convert.ToUInt16(strTemp, 16);
                comboBox_DevIndex.Enabled = false;
                comboBox_Mode.Enabled = false;
                button_res.Enabled = false;
            }
            else if (strTemp.Contains("USBCAN2"))//创芯科技CAN盒
            {
                candevtype = 0;
                m_devtype = 4;
                comboBox_DevIndex.Enabled = true;
                comboBox_Mode.Enabled = true;
                button_res.Enabled = true;
            }
        }

        private void comboBox_DevIndex_SelectedIndexChanged(object sender, EventArgs e)
        {
            m_devind = (UInt32)comboBox_DevIndex.SelectedIndex;
        }
        void ChecksPcan()
        {
            TPCANStatus stsResult;
            uint iChannelsCount;
            bool bIsFD;
            try
            {
                stsResult = PCANBasic.GetValue(PCANBasic.PCAN_NONEBUS, TPCANParameter.PCAN_ATTACHED_CHANNELS_COUNT, out iChannelsCount, sizeof(uint));
                if (stsResult == TPCANStatus.PCAN_ERROR_OK)
                {
                    TPCANChannelInformation[] info = new TPCANChannelInformation[iChannelsCount];

                    stsResult = PCANBasic.GetValue(PCANBasic.PCAN_NONEBUS, TPCANParameter.PCAN_ATTACHED_CHANNELS, info);
                    if (stsResult == TPCANStatus.PCAN_ERROR_OK)
                        // Include only connectable channels
                        foreach (TPCANChannelInformation channel in info)
                            if ((channel.channel_condition & PCANBasic.PCAN_CHANNEL_AVAILABLE) == PCANBasic.PCAN_CHANNEL_AVAILABLE)
                            {
                                bIsFD = (channel.device_features & PCANBasic.FEATURE_FD_CAPABLE) == PCANBasic.FEATURE_FD_CAPABLE;
                                comboBox_devtype.Items.Add(FormatChannelName(channel.channel_handle, bIsFD));
                            }
                }
                comboBox_devtype.SelectedIndex = comboBox_devtype.Items.Count - 1;
                if (stsResult != TPCANStatus.PCAN_ERROR_OK)
                    LogWork.Text = GetFormatedError(stsResult);
            }
            catch
            {
                LogWork.Text = "Unable to find the library: PCANBasic.dll !";
            }
        }
        
        #region CellLevel_FUN
        /// <summary>
        /// 新建一个方法,另一个窗口调用这个方法,修改本窗口的值
        /// </summary>
        /// <param name="number"></param>

        public void Change_V1Max(UInt16 number)
        {
            cellLevel.VOL_LV1max = number;
        }
        public void Change_V1Min(UInt16 number)
        {
            cellLevel.VOL_LV1min = number;
        }
        public void Change_V2Max(UInt16 number)
        {
            cellLevel.VOL_LV2max = number;
        }
        public void Change_V2Min(UInt16 number)
        {
            cellLevel.VOL_LV2min = number;
        }
        public void Change_V3Max(UInt16 number)
        {
            cellLevel.VOL_LV3max = number;
        }
        public void Change_V3Min(UInt16 number)
        {
            cellLevel.VOL_LV3min = number;
        }
        public void Change_V4Max(UInt16 number)
        {
            cellLevel.VOL_LV4max = number;
        }
        public void Change_V4Min(UInt16 number)
        {
            cellLevel.VOL_LV4min = number;
        }
        public void Change_T1Max(UInt16 number)
        {
            cellLevel.TEMP_LV1max = number;
        }
        public void Change_T1Min(UInt16 number)
        {
            cellLevel.TEMP_LV1min = number;
        }
        public void Change_T2Max(UInt16 number)
        {
            cellLevel.TEMP_LV2max = number;
        }
        public void Change_T2Min(UInt16 number)
        {
            cellLevel.TEMP_LV2min = number;
        }
        public void Change_T3Max(UInt16 number)
        {
            cellLevel.TEMP_LV3max = number;
        }
        public void Change_T3Min(UInt16 number)
        {
            cellLevel.TEMP_LV3min = number;
        }
        public void Change_T4Max(UInt16 number)
        {
            cellLevel.TEMP_LV4max = number;
        }
        public void Change_T4Min(UInt16 number)
        {
            cellLevel.TEMP_LV4min = number;
        }

        public UInt16 Change_V1Max( )
        {
            return cellLevel.VOL_LV1max;
        }
        public UInt16 Change_V1Min( )
        {
            return cellLevel.VOL_LV1min ;
        }
        public UInt16 Change_V2Max( )
        {
            return cellLevel.VOL_LV2max  ;
        }
        public UInt16 Change_V2Min()
        {
            return cellLevel.VOL_LV2min ;
        }
        public UInt16 Change_V3Max()
        {
            return cellLevel.VOL_LV3max ;
        }
        public UInt16 Change_V3Min()
        {
            return cellLevel.VOL_LV3min ;
        }
        public UInt16 Change_V4Max()
        {
            return cellLevel.VOL_LV4max ;
        }
        public UInt16 Change_V4Min()
        {
            return cellLevel.VOL_LV4min;
        }
        public UInt16 Change_T1Max()
        {
            return cellLevel.TEMP_LV1max ;
        }
        public UInt16 Change_T1Min()
        {
            return cellLevel.TEMP_LV1min ;
        }
        public UInt16 Change_T2Max()
        {
            return cellLevel.TEMP_LV2max ;
        }
        public UInt16 Change_T2Min()
        {
            return cellLevel.TEMP_LV2min ;
        }
        public UInt16 Change_T3Max()
        {
            return cellLevel.TEMP_LV3max ;
        }
        public UInt16 Change_T3Min()
        {
            return cellLevel.TEMP_LV3min;
        }
        public UInt16 Change_T4Max()
        {
            return cellLevel.TEMP_LV4max;
        }
        public UInt16 Change_T4Min()
        {
            return cellLevel.TEMP_LV4min ;
        }
        #endregion
        /// <summary>
        /// 按键弹出设置电压温度范围阈值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_1(object sender, EventArgs e)
        {
            SetCellInfo setcellinfo = new SetCellInfo();
            //弹出对话框,
            setcellinfo.ShowDialog(this);//this 必不可少
        }
        string BoxText_str = " ";
        Color BoxColor_str = new Color();
        public string MessageBoxText_SlaveAck()
        {
            return BoxText_str;
        }
        public Color MessageBoxText_color()
        {
            return BoxColor_str;
        }
        void MainSlaveModeChange()
        {
            if(InSlaveModetickcnt > 9)
            {
                InSlaveModetickcnt = 0;
                InSlaveMode.SlaveModeStart = 0;
                BoxText_str = "上位机与 BMU 握手失败";
                BoxColor_str = Color.Red;
                MyMessageBox mmb = new MyMessageBox();
                //弹出对话框,提示成功与否
                mmb.ShowDialog(this);//this 必不可少
            }
            if (InSlaveCheck_updata == 1)
            {
                InSlaveCheck_updata = 0;
                if (InSlaveMode.SlaveCheckAck == 1)
                {
                    BoxText_str = "上位机与 BMU 校准成功";
                    BoxColor_str = Color.Green;
                }
                else
                {
                    BoxText_str = "上位机与 BMU 校准失败";
                    BoxColor_str = Color.Red;
                }
                MyMessageBox mmb = new MyMessageBox();
                //弹出对话框,提示成功与否
                mmb.ShowDialog(this);//this 必不可少

                InSlaveMode.SlaveCheckAck = 0;
                InSlaveMode.SlaveCheckSend = 0;              
            }
            if (InSlaveMode_updata == 1)
            {
                InSlaveMode_updata = 0;
                if (InSlaveMode.SlaveModeAck == 1)
                {
                    label15.Text = "握手成功";
                    BoxText_str = "上位机与 BMU 握手成功";
                    BoxColor_str = Color.Green;
                }
                else
                {
                    BoxColor_str = Color.Red;
                    BoxText_str = "上位机与 BMU 握手失败";
                }
                MyMessageBox mmb = new MyMessageBox();
                //弹出对话框,提示成功与否
                mmb.ShowDialog(this);//this 必不可少
            }
            if (InSlaveAssignaddr_updata == 1)
            {
                InSlaveAssignaddr_updata = 0;
                if (InSlaveMode.SlaveAddrAck == 1)
                {
                    BoxText_str = "BMU 编码成功";
                    BoxColor_str = Color.Green;

                }
                else
                {
                    BoxColor_str = Color.Red;
                    BoxText_str = "BMU 编码失败";
                }
                MyMessageBox mmb = new MyMessageBox();
                //弹出对话框,提示成功与否
                mmb.ShowDialog(this);//this 必不可少
                InSlaveMode.SlaveAddrAck = 0;
                InSlaveMode.SlaveAddrSend = 0;
            }
            if(faultlogState_S.nvmErrorCode > 0)
            {
                if (faultlogState_S.nvmErrorCode == 1) BoxText_str = "NVM日志 握手失败";
                if (faultlogState_S.nvmErrorCode == 2) BoxText_str = "NVM日志 CRC8校验失败";
                if (faultlogState_S.nvmErrorCode == 3) BoxText_str = "NVM日志 CRC32校验失败";
                BoxColor_str = Color.Red;
                faultlogState_S.nvmErrorCode = 0;
                //MyMessageBox mmb = new MyMessageBox();
                //弹出对话框,提示成功与否
                //mmb.ShowDialog(this);//this 必不可少
                
            }
            if (faultlogState_S.tfErrorCode > 0)
            {
                if (faultlogState_S.tfErrorCode == 1) BoxText_str = "TF日志 握手失败";
                if (faultlogState_S.tfErrorCode == 2) BoxText_str = "TF日志 CRC8校验失败";
                if (faultlogState_S.tfErrorCode == 3) BoxText_str = "TF日志 CRC32校验失败";
                BoxColor_str = Color.Red;
                faultlogState_S.tfErrorCode = 0;
                MyMessageBox mmb = new MyMessageBox();
                //弹出对话框,提示成功与否
                mmb.ShowDialog(this);//this 必不可少
            }
        }
        void InSlaveModeStateInit()
        {
            label15.Text = " ";
            dataGridViewcan.Rows.Clear();
            clear_fifo();
            dataGridViewcan.Rows.Add(500);
            InSlaveMode_updata = 0;
            InSlaveCheck_updata = 0;
            InSlaveAssignaddr_updata = 0;
            InSlaveMode.SlaveCheckAck = 0;
            InSlaveMode.SlaveModeAck = 0;
            InSlaveMode.SlaveAddrAck = 0;
            InSlaveMode.SlaveAddrSend = 0;
            InSlaveMode.SlaveCheckSend = 0;
            InSlaveMode.SlaveModeSend = 0;
            InSlaveMode.SlaveModeStart = 0;
        }
        private void add_dbc_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            string str;
            byte CM_cnt = 0;
            ushort dbcLineAll = 0, BA_DEF_cnt = 0;
            fd.Filter = "dbc文件(*.dbc)|*.dbc";
            
            if (fd.ShowDialog() == DialogResult.OK)
            {
                dbcFileName = fd.FileName;
                StreamReader sR4 = new StreamReader(dbcFileName, Encoding.ASCII);
                LogWork.Text = "dbc文件加载成功";
                do
                {

                    str = sR4.ReadLine();
                    if(str != null)
                    {
                        dbcLineAll++;
                        if (str.Contains("CM_"))
                        {
                            if (++CM_cnt == 3 && dbcCM_Line == 0)
                            {
                                dbcCM_Line = dbcLineAll;
                                LogWork.Text = dbcLineAll.ToString();
                            }
                        }
                        if (str.Contains("BA_DEF_"))
                        {
                            if (++BA_DEF_cnt == 10 && dbcBA_DEF_Line == 0)
                            {
                                dbcBA_DEF_Line = dbcLineAll;
                                LogWork.Text = dbcLineAll.ToString();
                                break;
                            }
                        }
                    }
                    
                    
                } while (str != null);

                dbc_start.Enabled = true;
                dbc_stop.Enabled = true;
                DBCstartFlag = 1;
                sR4.Close();
            }
            else
            {
                LogWork.Text = "dbc文件加载失败";
                dbc_start.Enabled = false;
                dbc_stop.Enabled = false;
            }
        }

        private void dbc_start_Click(object sender, EventArgs e)
        {
            DBCstartFlag = 1;
            treeView_dbc.Nodes.Clear();
            ProcessDBCserve();
        }

        private void dbc_stop_Click(object sender, EventArgs e)
        {
            DBCstartFlag = 0;
        }
        void updata_linsece()
        {
            tabControl11.Visible = true;
            label131.Visible = false;
        }
        void LogIn()
        {        
            panel75.Visible = false;
            divider18.Visible = true;
            panel36.Visible = true;
            tabControl11.Visible = true;
            this.BackgroundImage = null;
            //Form size
            this.Width = Screen.PrimaryScreen.Bounds.Width;
            this.Height = Screen.PrimaryScreen.Bounds.Height - 40;
            this.FormBorderStyle = FormBorderStyle.Sizable;
            if (SYSSETFACINFO == false)
            {
                timerSys.Enabled = true;
            }
        }
        void LogInCheck()
        {
            if (user_name.Text == "admin" && user_password.Text == "admin")
            {
                LogIn();
            }
            else
            {
                MessageBox.Show("请输入正确的用户名和密码", "登录提示");
            }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            LogInCheck();
        }

        #region bBALAswitch
        /// <summary>
        /// 打包成一个标定控制帧
        /// </summary>
        /// <param name="dev">设备</param>
        /// <param name="operation">操作</param>
        /// <param name="signal_num">操作指令序号</param>
        /// <param name="signal_val">操作指令内容</param>
        /// <returns></returns>
        public string Send_ClbComm_pack(byte dev, byte operation, UInt16 signal_num, Int32 signal_val)
        {
            byte[] clbarray = new byte[8];
            string[] buff = new string[8];
            string str;

            //my_push_clb(signal_num);
            if (isclfaultcCom(signal_num) == true)
            {
                if (operation == CLB_OPT_WRITE)
                    FaultJsonResults[signal_num - (UInt16)CLB_SIGNALNUM.CLB_W_CELLOV_LV1].Operation = "Writing";
                else
                    FaultJsonResults[signal_num - (UInt16)CLB_SIGNALNUM.CLB_W_CELLOV_LV1].Operation = "Reading";
            }
            UInt16 status = (UInt16)((dev << 14) | (operation << 12) | (signal_num & 0x0FFF));

            clbarray[0] = (byte)(status>>8);
            clbarray[1] =(byte)status;

            clbarray[2] = (byte)(signal_val >> 24);
            clbarray[3] = (byte)(signal_val >> 16);
            clbarray[4] = (byte)(signal_val >> 8);
            clbarray[5] = (byte)signal_val;

            clbarray[6] = CLB_CRC_BASE;
            clbarray[7] = (byte)(clbarray[0] ^ clbarray[1] ^ clbarray[2] ^ clbarray[3] ^ clbarray[4] ^ clbarray[5] ^ clbarray[6]);
            for (byte i = 0; i < 8; i++)
            {
                buff[i] = clbarray[i].ToString("X2");
            }
            str = string.Join(" ", buff);
            return str; 
        }
        void CLB_ORDER_SLAVE_BALA_PAGE(byte en)
        {
            uint cellbala_comm_temp1 = 0, cellbala_comm_temp2 = 0;
            UInt16 signal_num_temp1 = 0, signal_num_temp2 = 0;
            if (BMS_CellVoltTempPage == 1)
            {
                signal_num_temp1 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE1_BALA_1;
                signal_num_temp2 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE1_BALA_2;
            }
            if (BMS_CellVoltTempPage == 2)
            {
                signal_num_temp1 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE2_BALA_1;
                signal_num_temp2 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE2_BALA_2;
            }
            if (BMS_CellVoltTempPage == 3)
            {
                signal_num_temp1 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE3_BALA_1;
                signal_num_temp2 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE3_BALA_2;
            }
            if (BMS_CellVoltTempPage == 4)
            {
                signal_num_temp1 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE4_BALA_1;
                signal_num_temp2 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE4_BALA_2;
            }
            if (BMS_CellVoltTempPage == 5)
            {
                signal_num_temp1 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE5_BALA_1;
                signal_num_temp2 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE5_BALA_2;
            }
            if (BMS_CellVoltTempPage == 6)
            {
                signal_num_temp1 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE6_BALA_1;
                signal_num_temp2 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE6_BALA_2;
            }
            if (BMS_CellVoltTempPage == 7)
            {
                signal_num_temp1 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE7_BALA_1;
                signal_num_temp2 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE7_BALA_2;
            }
            if (BMS_CellVoltTempPage == 8)
            {
                signal_num_temp1 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE8_BALA_1;
                signal_num_temp2 = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE8_BALA_2;
            }
            if ( en == 1)//1-32 -> 0-31
            {
                cellbala_comm_temp1 = 0xffffffff;
                cellbala_comm_temp2 = 0xffffffff;
            }
            string str1 = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, signal_num_temp1, (int)cellbala_comm_temp1);//
            my_push_send((uint)DBC_ID.CLB_CANID, str1, 1);
            str1 = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, signal_num_temp2, (int)cellbala_comm_temp2);//
            my_push_send((uint)DBC_ID.CLB_CANID, str1, 1);

        }
        /// <summary>
        ///  发送均衡控制指令,实现点对点的均衡控制开/关
        /// </summary>
        /// <param name="bBalaNumber">电芯编号1-128</param>
        /// <param name="en">en = 1:开;en = 0:关</param>
        private void CLB_ORDER_SLAVE_BALA(UInt16 bBalaNumber,byte en)
        {
            Int32 cellbala_comm_temp1 = 0, cellbala_comm_temp2 = 0;
            UInt16 signal_num_temp = 0;
            if (cb_cellbalaEn.Checked == false)
                return;
            if (bBalaNumber < 33)
            {
                if (BMS_CellVoltTempPage == 1)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE1_BALA_1;
                if (BMS_CellVoltTempPage == 2)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE2_BALA_1;
                if (BMS_CellVoltTempPage == 3)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE3_BALA_1;
                if (BMS_CellVoltTempPage == 4)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE4_BALA_1;
                if (BMS_CellVoltTempPage == 5)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE5_BALA_1;
                if (BMS_CellVoltTempPage == 6)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE6_BALA_1;
                if (BMS_CellVoltTempPage == 7)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE7_BALA_1;
                if (BMS_CellVoltTempPage == 8)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE8_BALA_1;
                for (byte i = 0; i < 32; i++)
                {
                    if (en > 0)
                    {
                        if (DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i] > 0 || bBalaNumber == i)
                        {
                            cellbala_comm_temp1 |= (Int32)(0x01 << (i));
                        }
                        /*
                        if (bBalaNumber == i)
                        {
                            DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i ] = 1;
                        }*/
                    }
                    else
                    {
                        if (DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i] > 0 && bBalaNumber != i)
                        {
                            cellbala_comm_temp1 |= (Int32)(0x01 << (i));
                        }
                        /*
                        if (DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i] > 0 && bBalaNumber == i)
                        {
                            DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i] = 0;
                        }*/
                    }
                }
                string str = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, signal_num_temp, cellbala_comm_temp1);//
                my_push_send((uint)DBC_ID.CLB_CANID, str, 1);
            }
            else
            {
                if (BMS_CellVoltTempPage == 1)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE1_BALA_2;
                if (BMS_CellVoltTempPage == 2)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE2_BALA_2;
                if (BMS_CellVoltTempPage == 3)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE3_BALA_2;
                if (BMS_CellVoltTempPage == 4)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE4_BALA_2;
                if (BMS_CellVoltTempPage == 5)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE5_BALA_2;
                if (BMS_CellVoltTempPage == 6)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE6_BALA_2;
                if (BMS_CellVoltTempPage == 7)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE7_BALA_2;
                if (BMS_CellVoltTempPage == 8)
                    signal_num_temp = (UInt16)MyDefine.CLB_SIGNALNUM.CLB_ORDER_SLAVE8_BALA_2;
                for (byte i = 32; i < BMS_PAGECELLNUMBER_Max; i++)
                {
                    if (en > 0)
                    {
                        if (DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i] > 0 || bBalaNumber == i)
                        {
                            cellbala_comm_temp2 |= (Int32)(0x01 << (i - 32));
                        }
                        /*
                        if(bBalaNumber == i)
                        {
                            DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i] = 1;
                        }*/
                    }
                    else
                    {
                        if (DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i] > 0 && bBalaNumber != i)
                        {
                            cellbala_comm_temp2 |= (Int32)(0x01 << (i - 32));
                        }
                        /*
                        if (DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i] > 0 && bBalaNumber == i)
                        {
                            DV_BMS_Cell_BALA_FB[BMS_PAGECELLNUMBER_Max * (BMS_CellVoltTempPage - 1) + i] = 0;
                        }*/
                    }
                }
                string str = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, signal_num_temp, cellbala_comm_temp2);//
                my_push_send((uint)DBC_ID.CLB_CANID, str, 1);
            }
        }
        /// <summary>
        /// 发送均衡控制指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bBALAswitch1_Click(object sender, EventArgs e)
        {
            byte number = 1;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch2_Click(object sender, EventArgs e)
        {
            byte number = 2; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch3_Click(object sender, EventArgs e)
        {
            byte number = 3; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch4_Click(object sender, EventArgs e)
        {
            byte number = 4; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch5_Click(object sender, EventArgs e)
        {
            byte number = 5; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch6_Click(object sender, EventArgs e)
        {
            byte number = 6; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch7_Click(object sender, EventArgs e)
        {
            byte number = 7; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
            private void bBALAswitch8_Click(object sender, EventArgs e)
        {
            byte number = 8; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch9_Click(object sender, EventArgs e)
        {
            byte number = 9; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch10_Click(object sender, EventArgs e)
        {
            byte number = 10; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch11_Click(object sender, EventArgs e)
        {
            byte number = 11; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch12_Click(object sender, EventArgs e)
        {
            byte number = 12; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch13_Click(object sender, EventArgs e)
        {
            byte number = 13; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch14_Click(object sender, EventArgs e)
        {
            byte number = 14;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch15_Click(object sender, EventArgs e)
        {
            byte number = 15; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch16_Click(object sender, EventArgs e)
        {
            byte number = 16; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch17_Click(object sender, EventArgs e)
        {
            byte number = 17; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch18_Click(object sender, EventArgs e)
        {
            byte number = 18; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch19_Click(object sender, EventArgs e)
        {
            byte number = 19; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch20_Click(object sender, EventArgs e)
        {
            byte number = 20; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch21_Click(object sender, EventArgs e)
        {
            byte number = 21; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch22_Click(object sender, EventArgs e)
        {
            byte number = 22; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch23_Click(object sender, EventArgs e)
        {
            byte number = 23; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch24_Click(object sender, EventArgs e)
        {
            byte number = 24; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch25_Click(object sender, EventArgs e)
        {
            byte number = 25; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch26_Click(object sender, EventArgs e)
        {
            byte number = 26; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch27_Click(object sender, EventArgs e)
        {
            byte number = 27; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch28_Click(object sender, EventArgs e)
        {
            byte number = 28; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch29_Click(object sender, EventArgs e)
        {
            byte number = 29; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch30_Click(object sender, EventArgs e)
        {
            byte number = 30; ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch31_Click(object sender, EventArgs e)
        {
            byte number = 31; 
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch32_Click(object sender, EventArgs e)
        {
            byte number = 32;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch33_Click(object sender, EventArgs e)
        {
            byte number = 33;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch34_Click(object sender, EventArgs e)
        {
            byte number = 34;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch35_Click(object sender, EventArgs e)
        {
            byte number = 35;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch36_Click(object sender, EventArgs e)
        {
            byte number = 36;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch37_Click(object sender, EventArgs e)
        {
            byte number = 37;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch38_Click(object sender, EventArgs e)
        {
            byte number = 38;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch39_Click(object sender, EventArgs e)
        {
            byte number =39;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch40_Click(object sender, EventArgs e)
        {
            byte number = 40;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch41_Click(object sender, EventArgs e)
        {
            byte number = 41;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch42_Click(object sender, EventArgs e)
        {
            byte number = 42;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch43_Click(object sender, EventArgs e)
        {
            byte number = 43;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch44_Click(object sender, EventArgs e)
        {
            byte number = 44;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch45_Click(object sender, EventArgs e)
        {
            byte number = 45;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch46_Click(object sender, EventArgs e)
        {
            byte number = 46;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch47_Click(object sender, EventArgs e)
        {
            byte number = 47;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch48_Click(object sender, EventArgs e)
        {
            byte number = 48;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch49_Click(object sender, EventArgs e)
        {
            byte number =49;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch50_Click(object sender, EventArgs e)
        {
            byte number = 50;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch51_Click(object sender, EventArgs e)
        {
            byte number = 51;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }

        private void bBALAswitch52_Click(object sender, EventArgs e)
        {
            byte number = 52;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch53_Click(object sender, EventArgs e)
        {
            byte number = 53;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch54_Click(object sender, EventArgs e)
        {
            byte number = 54;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch55_Click(object sender, EventArgs e)
        {
            byte number = 55;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch56_Click(object sender, EventArgs e)
        {
            byte number = 56;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch57_Click(object sender, EventArgs e)
        {
            byte number = 57;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch58_Click(object sender, EventArgs e)
        {
            byte number = 58;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch59_Click(object sender, EventArgs e)
        {
            byte number = 59;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch60_Click(object sender, EventArgs e)
        {
            byte number = 60;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch61_Click(object sender, EventArgs e)
        {
            byte number = 61;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch62_Click(object sender, EventArgs e)
        {
            byte number = 62;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch63_Click(object sender, EventArgs e)
        {
            byte number = 63;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        private void bBALAswitch64_Click(object sender, EventArgs e)
        {
            byte number = 64;
            ushort CellNumReal = (ushort)(CellInfo[number - 1].CellNumReal);
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(CellNumReal, 1);
            }
        }
        /*
        void bBALAswitch65_Click(object sender, EventArgs e)
        {
            byte number = 65;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch66_Click(object sender, EventArgs e)
        {
            byte number = 66;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch67_Click(object sender, EventArgs e)
        {
            byte number = 67;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch68_Click(object sender, EventArgs e)
        {
            byte number = 68;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch69_Click(object sender, EventArgs e)
        {
            byte number = 69;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch70_Click(object sender, EventArgs e)
        {
            byte number = 70;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch71_Click(object sender, EventArgs e)
        {
            byte number = 71;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch72_Click(object sender, EventArgs e)
        {
            byte number = 72;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch73_Click(object sender, EventArgs e)
        {
            byte number = 73;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch74_Click(object sender, EventArgs e)
        {
            byte number = 74;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch75_Click(object sender, EventArgs e)
        {
            byte number = 75;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch76_Click(object sender, EventArgs e)
        {
            byte number = 76;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch77_Click(object sender, EventArgs e)
        {
            byte number = 77;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch78_Click(object sender, EventArgs e)
        {
            byte number = 78;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch79_Click(object sender, EventArgs e)
        {
            byte number = 79;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch80_Click(object sender, EventArgs e)
        {
            byte number = 80;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch81_Click(object sender, EventArgs e)
        {
            byte number = 81;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch82_Click(object sender, EventArgs e)
        {
            byte number = 82;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch83_Click(object sender, EventArgs e)
        {
            byte number = 83;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch84_Click(object sender, EventArgs e)
        {
            byte number = 84;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch85_Click(object sender, EventArgs e)
        {
            byte number = 85;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch86_Click(object sender, EventArgs e)
        {
            byte number = 86;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch87_Click(object sender, EventArgs e)
        {
            byte number = 87;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch88_Click(object sender, EventArgs e)
        {
            byte number = 88;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch89_Click(object sender, EventArgs e)
        {
            byte number = 89;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch90_Click(object sender, EventArgs e)
        {
            byte number = 90;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch91_Click(object sender, EventArgs e)
        {
            byte number = 91;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch92_Click(object sender, EventArgs e)
        {
            byte number = 92;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch93_Click(object sender, EventArgs e)
        {
            byte number = 93;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch94_Click(object sender, EventArgs e)
        {
            byte number = 94;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch95_Click(object sender, EventArgs e)
        {
            byte number = 95;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch96_Click(object sender, EventArgs e)
        {
            byte number = 96;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch97_Click(object sender, EventArgs e)
        {
            byte number = 97;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch98_Click(object sender, EventArgs e)
        {
            byte number = 98;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch99_Click(object sender, EventArgs e)
        {
            byte number = 99;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch100_Click(object sender, EventArgs e)
        {
            byte number = 100;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch101_Click(object sender, EventArgs e)
        {
            byte number = 101;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch102_Click(object sender, EventArgs e)
        {
            byte number = 102;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch103_Click(object sender, EventArgs e)
        {
            byte number = 103;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch104_Click(object sender, EventArgs e)
        {
            byte number = 104;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch105_Click(object sender, EventArgs e)
        {
            byte number = 105;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch106_Click(object sender, EventArgs e)
        {
            byte number = 106;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch107_Click(object sender, EventArgs e)
        {
            byte number = 107;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch108_Click(object sender, EventArgs e)
        {
            byte number = 108;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch109_Click(object sender, EventArgs e)
        {
            byte number = 109;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch110_Click(object sender, EventArgs e)
        {
            byte number = 110;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch111_Click(object sender, EventArgs e)
        {
            byte number = 111;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch112_Click(object sender, EventArgs e)
        {
            byte number = 112;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch113_Click(object sender, EventArgs e)
        {
            byte number = 113;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch114_Click(object sender, EventArgs e)
        {
            byte number = 114;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch115_Click(object sender, EventArgs e)
        {
            byte number = 115;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }

        private void bBALAswitch116_Click(object sender, EventArgs e)
        {
            byte number = 116;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch117_Click(object sender, EventArgs e)
        {
            byte number = 117;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch118_Click(object sender, EventArgs e)
        {
            byte number = 118;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch119_Click(object sender, EventArgs e)
        {
            byte number = 119;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch120_Click(object sender, EventArgs e)
        {
            byte number = 120;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch121_Click(object sender, EventArgs e)
        {
            byte number = 121;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch122_Click(object sender, EventArgs e)
        {
            byte number = 122;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch123_Click(object sender, EventArgs e)
        {
            byte number = 123;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch124_Click(object sender, EventArgs e)
        {
            byte number = 124;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch125_Click(object sender, EventArgs e)
        {
            byte number = 125;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch126_Click(object sender, EventArgs e)
        {
            byte number = 126;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch127_Click(object sender, EventArgs e)
        {
            byte number = 127;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        private void bBALAswitch128_Click(object sender, EventArgs e)
        {
            byte number = 128;
            if (CellInfo[number - 1].cellstatetext == "均衡已开")
            {
                CLB_ORDER_SLAVE_BALA(number, 0);
            }
            if (CellInfo[number - 1].cellstatetext == "均衡未开")
            {
                CLB_ORDER_SLAVE_BALA(number, 1);
            }
        }
        */
        #endregion


        private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.CellStyle.BackColor = Color.Aquamarine;
            DataGridViewTextBoxEditingControl cellEdit_m = new DataGridViewTextBoxEditingControl();
            cellEdit_m = (DataGridViewTextBoxEditingControl)e.Control;
            cellEdit_m.SelectAll();
            //cellEdit_m.KeyPress -= Cells_KeyPress; //绑定事件
            if (sender is DataGridView)
            {
                DataGridView gridView = (DataGridView)sender;
                if (gridView.CurrentCell.ColumnIndex > 1)
                {
                   // cellEdit_m.KeyPress += Cells_KeyPress; //绑定事件
                }
            }
        }

        UInt16 Clb_ThreeNodeSignalNum1 = 0;
        UInt16 Clb_ThreeNodeSignalNum2 = 0;
        UInt16 Clb_ThreeNodeSignalNum3 = 0;
        UInt16 Clb_SecondNode = 0;
        UInt16 Clb_ThreeNode = 0;
        int Clb_Reply_unpack(ref MyDefine.pc_Calibration_observation_t dst_p, byte[] arry)
        {
            MyDefine e = new MyDefine();
            dst_p.device = e.Clb_unpack_right_shift_u8(arry[0], 6, 0xff);
            dst_p.operation = e.Clb_unpack_right_shift_u8(arry[0], 4, 0x30);
            dst_p.signal_num = (ushort)(( arry[0] & 0x0f ) << 8 | arry[1]);
            dst_p.signal_val = (uint)(arry[2]<<24| arry[3] << 16 | arry[4] << 8 | arry[5]);
            dst_p.crc_base = e.Clb_unpack_right_shift_u8(arry[6], 0, 0xff);
            dst_p.crc8 = (byte)(arry[0] ^ arry[1] ^ arry[2] ^ arry[3] ^ arry[4] ^ arry[5] ^ arry[6]);
            if (dst_p.crc8 != arry[7])
            {
                return (-1);
            }
            return 1;
        }
        bool isReadFacInfo(pc_Calibration_observation_t scr_p)
        {
            if (scr_p.signal_num >= (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_CLUSTERCELLNUM && scr_p.signal_num <= (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_TEST7)
                return true;
            else
                return false;
        }
        bool isCheckFacCrc(pc_Calibration_observation_t scr_p)
        {
            if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_CRC32 && scr_p.operation == CLB_OPT_REPLY)
                return true;
            else
                return false;
        }
        bool isReadRtcCom(pc_Calibration_observation_t scr_p)
        {
            if (scr_p.signal_num >= (UInt16)CLB_SIGNALNUM.CLB_W_RTC_TIME && scr_p.signal_num <= (UInt16)CLB_SIGNALNUM.CLB_W_RTC_DAY)
                return true;
            else
                return false;
        }
        bool isclfaultcCom(UInt16 signal_num)
        {
            if(signal_num >= (UInt16)CLB_SIGNALNUM.CLB_W_CELLOV_LV1 &&
                signal_num <= (UInt16)CLB_SIGNALNUM.CLB_W_MAX  )
                return true;
            else
                return false;
        }

        void testrtc()
        {
            byte[] arrybuff = new byte[8];
            UInt16 status = (3 << 14) | (3 << 12) | (551 & 0x0FFF);
            arrybuff[0] = (byte)(status >> 8);
            arrybuff[1] = (byte)(status >> 0);
            arrybuff[2] = 0x18;
            arrybuff[3] = 0x08;
            arrybuff[4] = 0x0f;
            arrybuff[5] = 0x04;
            arrybuff[6] = 0x3c;
            arrybuff[7] = (byte)(arrybuff[0] ^ arrybuff[1] ^ arrybuff[2] ^ arrybuff[3] ^ arrybuff[4] ^ arrybuff[5] ^ arrybuff[6]);
            Clb_Reply((uint)DBC_ID.CLB_CANID, arrybuff);
        }
        public void my_push_clb(UInt16 clbdata)
        {
            if (CircularBuff_clb.count < SENDBUFFSIZE)
            {
                clbData[CircularBuff_clb.head] = clbdata;
                CircularBuff_clb.head = (UInt16)((CircularBuff_clb.head + 1) % SENDBUFFSIZE);
                CircularBuff_clb.count++;
            } 
        }
        public bool my_pop_clb(UInt16 clbdata)
        {
            if (CircularBuff_clb.count == 0)
            {
                return false;
            }
            UInt16 databuff = clbData[CircularBuff_clb.tail];
            CircularBuff_clb.tail = (UInt16)((CircularBuff_clb.tail + 1) % SENDBUFFSIZE);
            CircularBuff_clb.count--;
            if (clbdata == databuff)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        pc_Calibration_observation_t OutPutClbRec = new pc_Calibration_observation_t();
        string ReadRTCday = "", ReadRTCtime= "";
        bool FacCheckSucceeFlag = false;//握手成功标志位
        /// <summary>
        /// 自定义标定协议解包
        /// </summary>
        /// <param name="CanID"></param>
        /// <param name="arry"></param>
        void Clb_Reply(uint CanID, byte[] arry)
        {
            pc_Calibration_observation_t scr_p = new pc_Calibration_observation_t(); 
            if (CanID != (uint)DBC_ID.CLB_CANID)
                return;
            if(1 == Clb_Reply_unpack(ref scr_p, arry))
            {
                if (isReadFacInfo(scr_p) == true)//读出厂信息,
                {
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_CLUSTERCELLNUM)
                        FactoryInfo.ClusterCellNum = (UInt16)scr_p.signal_val;
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_AFECELLNUM)
                        FactoryInfo.AfeCellNum = (UInt16)scr_p.signal_val;
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_PACKNUM)
                        FactoryInfo.PackNum = (UInt16)scr_p.signal_val;
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_BMUCellNum)
                        FactoryInfo.BMUCellNum = (UInt16)scr_p.signal_val;
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_BMUAfeNum)
                        FactoryInfo.BMUAfeNum = (UInt16)scr_p.signal_val;
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_SWVersion)
                        FactoryInfo.SWVersion = (UInt16)scr_p.signal_val;
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_HWVersion)                   
                        FactoryInfo.HWVersion = (UInt16)scr_p.signal_val;                   
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_SNNum)                    
                        FactoryInfo.SNNum = (UInt16)scr_p.signal_val;                    
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_TEST6)                   
                        FactoryInfo.Test6 = (UInt16)scr_p.signal_val;                    
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_TEST7)                    
                        FactoryInfo.Test7 = (UInt16)scr_p.signal_val;                    
                }
                if (isCheckFacCrc(scr_p) == true)//设置出厂信息,握手校验
                {
                    if(scr_p.signal_val  == GetFacCrc32Val(FactoryInfo))
                    {
                        FactoryInfo.crc32 = scr_p.signal_val;
                        FacCheckSucceeFlag = true;
                        BMS_BMUCellNum = FactoryInfo.BMUCellNum;
                    }
                }
                if (isReadRtcCom(scr_p) == true)//读RTC的时间
                {
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_RTC_DAY)
                    {
                        ReadRTCday = "20"+ ((byte)(scr_p.signal_val >> 24)).ToString() + "/" + ((byte)(scr_p.signal_val >> 16)).ToString() + "/" + ((byte)(scr_p.signal_val >> 8)).ToString();
                    }
                    if (scr_p.signal_num == (UInt16)CLB_SIGNALNUM.CLB_W_RTC_TIME)
                    {
                        ReadRTCtime = ((byte)(scr_p.signal_val >> 16)).ToString() + ":" + ((byte)(scr_p.signal_val >> 8)).ToString() + ":" + ((byte)scr_p.signal_val).ToString();
                    }
                    textBox42.Text = ReadRTCday+  " " + ReadRTCtime;
                }
                if( isclfaultcCom(scr_p.signal_num) == true)//标定故障阈值
                {
                   // if(my_pop_clb(scr_p.signal_num))
                    FaultJsonResults[scr_p.signal_num - (UInt16)CLB_SIGNALNUM.CLB_W_CELLOV_LV1].Operation = "Success";
                    if (File.Exists(FaultClbJSONFilePath) == true)
                    {
                        FaultJsonResults[scr_p.signal_num - (UInt16)CLB_SIGNALNUM.CLB_W_CELLOV_LV1].Val = scr_p.signal_val.ToString();
                        
                        //WriteJSONListToJsonFile(FaultClbJSONFilePath,FaultJsonResults);
                    }                    
                }
                
            }
        }
        
        bool threshold_dir = true;
       
        private void treeView1_fun_AfterSelect(object sender, TreeViewEventArgs e)
        {
            byte[] TempArray = new byte[8];
            if (e.Action.ToString() == "ByMouse" || e.Action.ToString() == "ByKeyboard")
            {
                TreeNode treenode = treeView1_fun.SelectedNode;
                MyDefine Myd = new MyDefine();
                foreach (string st in Myd.ControlFun)
                {
                    if (st.Contains(treenode.Text.Trim()))
                    {
                        string[] sArray = st.Split('-');
                        UInt16 signum = Convert.ToUInt16(sArray[1]);
                        Int32 setvalue1 = (Int32)(Convert.ToByte(textBox50.Text)<<24 | Convert.ToByte(textBox51.Text)<<16| Convert.ToByte(textBox52.Text)<<8| Convert.ToByte(textBox53.Text));
                        TempArray[0] = (byte)(0X10 | (byte)(signum >> 8));
                        TempArray[1] = (byte)signum;
                        TempArray[2] = Convert.ToByte(textBox50.Text);
                        TempArray[3] = Convert.ToByte(textBox51.Text);
                        TempArray[4] = Convert.ToByte(textBox52.Text);
                        TempArray[5] = Convert.ToByte(textBox53.Text);
                        TempArray[7] = (byte)(TempArray[0] ^ TempArray[1] ^ TempArray[2] ^ TempArray[3] ^ TempArray[4] ^ TempArray[5] ^ CLB_CRC_BASE);
                        textBox44.Text = TempArray[0].ToString("X");
                        textBox49.Text = TempArray[1].ToString("X");
                        textBox54.Text = TempArray[7].ToString("X");
                        textBox55.Text = treenode.Text;
                        textBox55.ForeColor = Color.Black;
                    }
                }
            }
        }
      

        private void button20_Click(object sender, EventArgs e)
        {
            connect con = new connect();
            //查询用户名与密码,用户名和密码需要和数据库中user_info表中User_name,Password相匹配
            string sql = "select * from user_info where User_name = '" + textBox35.Text + "'";

            //调用load方法建立open连接
            con.MySLQLload();  
            //查询语句，查询用户名与密码,用户名和密码需要和数据库中user_info表中User_name,Password相匹配
            //查询用户名
            con.comm = new MySqlCommand(sql, con.conn);
            con.dr = con.comm.ExecuteReader();
            con.dr.Read();
            
            //验证密码，
            if (textBox36.Text == con.dr.GetString("Password"))
            {
                MessageBox.Show("登录成功！");
                con.dr.Close();
            }
            else
                MessageBox.Show("登录失败！");  
        }
        /// <summary>
        /// 加载can设备
        /// </summary>
        void UploadCanDev()
        {
            comboBox_devtype.Items.Clear(); 
            comboBox_devtype.Items.Add("ZLG_USBCAN1");
            comboBox_devtype.Items.Add("ZLG_USBCAN2");
            comboBox_devtype.Items.Add("ZLG_USBCAN_E_U");
            comboBox_devtype.Items.Add("ZLG_USBCAN_2E_U");
            comboBox_devtype.Items.Add("ZLG_PCIECANFD-100U");
            comboBox_devtype.Items.Add("ZLG_PCIECANFD-200U");
            comboBox_devtype.Items.Add("ZLG_PCIECANFD-200U-EX");
            comboBox_devtype.Items.Add("ZLG_PCIECANFD-400U");
            comboBox_devtype.Items.Add("ZLG_USBCANFD-200U");
            comboBox_devtype.Items.Add("ZLG_USBCANFD-100U");
            comboBox_devtype.Items.Add("ZLG_USBCANFD-MNI");
            comboBox_devtype.Items.Add("USBCAN2");
            ChecksPcan();//获取PCAN设备列表
        }
        private void button2_Click_2(object sender, EventArgs e)
        {
            if (m_bOpen == 0)
                UploadCanDev();
        } 
        private void bt_cellallclose_Click(object sender, EventArgs e)
        {
            CLB_ORDER_SLAVE_BALA_PAGE(0);
        }
        private void bt_cellallopen_Click(object sender, EventArgs e)
        {
            CLB_ORDER_SLAVE_BALA_PAGE(1);
        }
      
        private void timer_clb_Tick()
        {
            //UInt16 time_signal_num = (UInt16)CLB_SIGNALNUM.CLB_W_CELLOV_LV1;
            // int temp = (time_signal_num - (UInt16)CLB_SIGNALNUM.CLB_W_CELLOV_LV1)*100 / ((UInt16)CLB_SIGNALNUM.CLB_W_CLUSTERSOCLOW_LV3 - (UInt16)CLB_SIGNALNUM.CLB_W_CELLOV_LV1);
            // string strID = "0X" + ((uint)DBC_ID.CLB_CANID).ToString("X2");
            // string strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, time_signal_num, 0);
            //// my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            // if (++time_signal_num > (UInt16)CLB_SIGNALNUM.CLB_W_CLUSTERSOCLOW_LV3)
            // {
            //     time_signal_num = (UInt16)CLB_SIGNALNUM.CLB_W_CELLOV_LV1;
            // }       
        }
        /// <summary>
        /// 从板模式回包
        /// </summary>
        /// <param name="CanID"></param>
        /// <param name="arry"></param>
        void CanInSlaveModeAck(uint CanID, byte[] arry)
        {
            uint CRC32 = 0, temp = 0;
            if (CanID == (uint)DBC_ID.INSLAVEMODE )
            {
                if(arry[0] == (byte)MyDefine.CANCOM_E.BS_ShakeHand_BMU)//bmu握手
                {

                    CRC32 = LibCal_Crc32Multi(arry, 4, (uint)MyDefine.CANCRC32INIT_E.BSI_ShakeHand_BMU, CRC32_FACTOR);
                    temp = (uint)(arry[4] << 24 | arry[5] << 16 | arry[6] << 8 | arry[7]);
                    if (CRC32 == temp)
                    {
                        InSlaveMode.SlaveModeAck = 1;
                        InSlaveMode_updata = 1;
                    }
                }
                if (arry[0] == (byte)MyDefine.CANCOM_E.BS_Check_BMU)//bmu校验
                {
                    InSlaveCheck_updata = 1;
                    Send_SlaveCheckcnt = 0;
                    CRC32 = LibCal_Crc32Multi(arry, 4, (uint)MyDefine.CANCRC32INIT_E.BSI_Check_BMU, CRC32_FACTOR);
                    temp = (uint)(arry[4] << 24 | arry[5] << 16 | arry[6] << 8 | arry[7]);
                    if (CRC32 == temp)
                    {
                        InSlaveMode.SlaveCheckAck = 1;
                        
                    }
                }
                if (arry[0] == (byte)MyDefine.CANCOM_E.BC_Assignaddr_BMU)//编码
                {
                    InSlaveAssignaddr_updata = 1;
                    Send_SlaveAssignaddrcnt = 0;
                    CRC32 = LibCal_Crc32Multi(arry, 4, (uint)MyDefine.CANCRC32INIT_E.BCI_Assignaddr_BMU, CRC32_FACTOR);
                    temp = (uint)(arry[4] << 24 | arry[5] << 16 | arry[6] << 8 | arry[7]);
                    if (CRC32 == temp)
                    {
                        InSlaveMode.SlaveAddrAck = 1;

                    }
                }

            }
        }
        /// <summary>
        /// 发送出厂信息握手,读出厂信息,与CRC32校验,
        /// </summary>
       byte FacInfoCheckCnt = 0;
        void Send_FacInfoCheck()
        {
            if (m_bOpen == 0 || comboBox_pcbType.SelectedIndex == 1)
                return;

            if (FacCheckSucceeFlag == true)
            {
                FacInfoCheckCnt = 0;
                return;
            }
            if (FacCheckSucceeFlag == false && FacInfoCheckCnt < 10 )
            {
                if (++FacInfoCheckCnt >= 10)
                {
                    //MessageBox.Show("上位机与 BCU 设备握手校验失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                string strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_CLUSTERCELLNUM, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_AFECELLNUM, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_PACKNUM, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_BMUCellNum, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_BMUAfeNum, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_SWVersion, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_HWVersion, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_SNNum, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_TEST6, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_TEST7, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_CRC32, 0);
                my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            }
        }
        // PC发送 ID=7FF: E8+rand(3字节随机)+4字节CRC32(初始值0x5648)
        // 从板回复  ID=7FF: E8+rand(3字节随机)+4字节CRC32(初始值0x3356)
        //uint LibCal_Crc32Multi(byte[] data, uint len, uint CRC_Init, uint factor)
        //data E7+rand(3字节随机);CRC_Init 初始值0x5648  ;factor  CRC32_FACTOR = 0x04C11DB7
        byte InSlaveModetickcnt = 0;
        void Send_InSlaveMode()
        {//1秒
            if (m_bOpen == 0||
                InSlaveModetickcnt > 10||
                InSlaveMode.SlaveModeAck == 1||
                InSlaveMode.SlaveModeStart == 0 )
                return;
            InSlaveModetickcnt++;
            int rand = 0;
            uint CRC32 = 0;
            byte[] buf = new byte[8] { (byte)MyDefine.CANCOM_E.BS_ShakeHand_PC, 0, 0, 0, 0, 0, 0, 0 };
            Random random = new Random();
            rand = random.Next()& 0x00ffffff;

            buf[1] = (byte)(rand>>16);
            buf[2] = (byte)(rand>>8);
            buf[3] = (byte)rand;

            CRC32 = LibCal_Crc32Multi(buf, 4, (uint)MyDefine.CANCRC32INIT_E.BSI_ShakeHand_PC , CRC32_FACTOR);

            buf[4] = (byte)(CRC32>>24);
            buf[5] = (byte)(CRC32>>16);
            buf[6] = (byte)(CRC32>>8);
            buf[7] = (byte)CRC32;
            my_push_send((uint)DBC_ID.INSLAVEMODE, buf, 1);
            InSlaveMode.SlaveModeSend = 1;
        }   


        private void dataGridViewcan_MouseEnter(object sender, EventArgs e)
        {
            MouseLocation = 1;//在can日志上
        }
        private void dataGridViewErr_MouseEnter(object sender, EventArgs e)
        {
            MouseLocation = 3;//在故障日志上
        }

        void GetTextBox54()
        {
            Byte[] TempArray = new Byte[8];
            TempArray[0] = Convert.ToByte("0X" + textBox44.Text, 16);
            TempArray[1] = Convert.ToByte("0X" + textBox49.Text, 16);
            TempArray[2] = Convert.ToByte("0X" + textBox50.Text, 16);
            TempArray[3] = Convert.ToByte("0X" + textBox51.Text, 16);
            TempArray[4] = Convert.ToByte("0X" + textBox52.Text, 16);
            TempArray[5] = Convert.ToByte("0X" + textBox53.Text, 16);
            TempArray[7] = (byte)(TempArray[0] ^ TempArray[1] ^ TempArray[2] ^ TempArray[3] ^ TempArray[4] ^ TempArray[5] ^ CLB_CRC_BASE);
            textBox54.Text = TempArray[7].ToString("X");
        }
        /// <summary>
        /// 功能控制页面,计算控制指令的CRC值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click_1(object sender, EventArgs e)
        {
            GetTextBox54();
        }
        /// <summary>
        /// 功能控制页面,发送控制指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button21_Click(object sender, EventArgs e)
        {
            Byte[] TempArray = new Byte[8];
            TempArray[0] = Convert.ToByte("0X" + textBox44.Text, 16);
            TempArray[1] = Convert.ToByte("0X" + textBox49.Text, 16);
            TempArray[2] = Convert.ToByte("0X" + textBox50.Text, 16);
            TempArray[3] = Convert.ToByte("0X" + textBox51.Text, 16);
            TempArray[4] = Convert.ToByte("0X" + textBox52.Text, 16);
            TempArray[5] = Convert.ToByte("0X" + textBox53.Text, 16);
            TempArray[6] = Convert.ToByte("0X" + textBox48.Text, 16);
            TempArray[7] = Convert.ToByte("0X" + textBox54.Text, 16);
            my_push_send((uint)DBC_ID.CLB_CANID, TempArray, 1);
        }
        /// <summary>
        /// 获取PC时间,填入textBox43文本框中
        /// </summary>
        void uptime()
        {
            textBox43.Text = System.DateTime.Now.ToString("T");
        }
        /// <summary>
        /// RTC标定按键,获取文本框中的日期,时间,按照协议发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button15_Click(object sender, EventArgs e)
        {
            Int32 setdaydata = 0,settimedata = 0;
            string[] array = new string[3] { "0","0","0"};
            setdaydata = (dateTimePicker1.Value.Year-2000)<<24 | dateTimePicker1.Value.Month<<16 | dateTimePicker1.Value.Day<<8 | (byte)dateTimePicker1.Value.DayOfWeek;           
            if (textBox43.Text.Contains(":"))
            {
                array = textBox43.Text.Split(':');
            }
            if (textBox43.Text.Contains("/"))
            {
                array = textBox43.Text.Split('/');
            }
            settimedata = Convert.ToInt32(array[0]) << 16 | Convert.ToInt32(array[1]) << 8;
            if (array.Length > 2)
                settimedata |=  Convert.ToInt32(array[2]);

            string strtext1 = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, (UInt16)CLB_SIGNALNUM.CLB_W_RTC_DAY, setdaydata);//
            my_push_send((uint)DBC_ID.CLB_CANID, strtext1, 1);
            string strtext2 = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, (UInt16)CLB_SIGNALNUM.CLB_W_RTC_TIME, settimedata);//
            my_push_send((uint)DBC_ID.CLB_CANID, strtext2, 1);
        }
        /// <summary>
        /// 获取当前时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click_1(object sender, EventArgs e)
        {
            uptime();
        }
        /// <summary>
        /// 限制按键输入数字0-9 , 删除 , / , : 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox43_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == 8) || (e.KeyChar == ':'))
            { }
            else
            {
                e.Handled = true;
            }
        }
        /// <summary>
        /// 焦点离开后,验证文本的正确性,是否满足时间格式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox43_Leave(object sender, EventArgs e)
        {
            if (textBox43.Text.Contains(":"))
            {
                string[] array = textBox43.Text.Split(':');
                if (Convert.ToInt32(array[0]) > 23)
                    array[0] = "23";
                if (Convert.ToInt32(array[1]) > 59)
                    array[1] = "59";

                if (array.Length > 2)
                {
                    if (Convert.ToInt32(array[2]) > 59)
                        array[2] = "59";
                    textBox43.Text = array[0] + array[1] + array[2];
                }
                else
                    textBox43.Text = array[0] + ":" + array[1] + ":00";
            }
            else
            {
                uptime();
            }
        }
        /// <summary>
        /// 发送读取RTC值的指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button14_Click(object sender, EventArgs e)
        {
            testrtc();
        }

        private void user_password_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar == 0X0d))//回车键
            {
                LogInCheck();
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            Byte[] TempArray = new Byte[8];
            textBox53.Text = "1";
            TempArray[0] = Convert.ToByte("0X" + textBox44.Text, 16);
            TempArray[1] = Convert.ToByte("0X" + textBox49.Text, 16);
            TempArray[2] = Convert.ToByte("0X" + textBox50.Text, 16);
            TempArray[3] = Convert.ToByte("0X" + textBox51.Text, 16);
            TempArray[4] = Convert.ToByte("0X" + textBox52.Text, 16);
            TempArray[5] = Convert.ToByte("0X" + textBox53.Text, 16); ;
            TempArray[6] = Convert.ToByte("0X" + textBox48.Text, 16);
            GetTextBox54();//计算crc
            TempArray[7] = Convert.ToByte("0X" + textBox54.Text, 16);
            my_push_send((uint)DBC_ID.CLB_CANID, TempArray, 1);
            textBox45.ForeColor = Color.Black;
            textBox45.AppendText("闭合指令发送成功"+ Environment.NewLine);
        }

        private void button16_Click_1(object sender, EventArgs e)
        {
            Byte[] TempArray = new Byte[8];
            textBox53.Text = "0";
            TempArray[0] = Convert.ToByte("0X" + textBox44.Text, 16);
            TempArray[1] = Convert.ToByte("0X" + textBox49.Text, 16);
            TempArray[2] = Convert.ToByte("0X" + textBox50.Text, 16);
            TempArray[3] = Convert.ToByte("0X" + textBox51.Text, 16);
            TempArray[4] = Convert.ToByte("0X" + textBox52.Text, 16);
            TempArray[5] = Convert.ToByte("0X" + textBox53.Text, 16); 
            TempArray[6] = Convert.ToByte("0X" + textBox48.Text, 16);
            GetTextBox54();//计算crc
            TempArray[7] = Convert.ToByte("0X" + textBox54.Text, 16);
            my_push_send((uint)DBC_ID.CLB_CANID, TempArray, 1);
            textBox45.ForeColor = Color.Black;
            textBox45.AppendText("断开指令发送成功"+ Environment.NewLine);
        }

        private void button23_Click_1(object sender, EventArgs e)
        {
            if(textBox44.PasswordChar == '-')
            {
                textBox44.PasswordChar = '\0';
                textBox49.PasswordChar = '\0';
                textBox50.PasswordChar = '\0';
                textBox51.PasswordChar = '\0';
                textBox52.PasswordChar = '\0';
                textBox48.PasswordChar = '\0';
                textBox54.PasswordChar = '\0';
                textBox53.PasswordChar = '\0';
            }
            else
            {
                textBox44.PasswordChar = '-';
                textBox49.PasswordChar = '-';
                textBox50.PasswordChar = '-';
                textBox51.PasswordChar = '-';
                textBox52.PasswordChar = '-';
                textBox48.PasswordChar = '-';
                textBox54.PasswordChar = '-';
                textBox53.PasswordChar = '-';
            }  
        }

        private void comboBox_pcbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            if (comboBox_pcbType.SelectedIndex == 0 && SYSSETFACINFO == false) 
            {
                //panel74.Visible = true;
                canMessage_stop = 1;//不显示
                cb_cellbalaEn.Enabled = true;
                bt_cellallclose.Enabled = true;
                bt_cellallopen.Enabled = true;
                button28.Visible = false;
                button29.Visible = false;
                textBox2.Visible = false;
                button35.Visible = false;
                label127.Text = "主板模式";
                label127.BackColor = Color.Gainsboro;
                comboBox_canbaud.SelectedIndex = 3;
            }
            if (comboBox_pcbType.SelectedIndex == 1)//从板模式
            {
                cb_cellbalaEn.Enabled = false;
                label127.Text = "单板采集模式";
                canMessage_stop = 1;//不显示
                label127.BackColor = Color.LimeGreen;
                BMS_CellVoltTempPage = 1;
                bt_cellallclose.Enabled = false;
                bt_cellallopen.Enabled = false;
                //panel74.Visible = false;
                button28.Visible = true;
                button29.Visible = true;
                button35.Visible = true;
                textBox2.Visible = true;
                comboBox_canbaud.SelectedIndex = 4;
            }
            
        }

        private bool PageUpdata(int dir)
        {
            bool rec = false;
            if (dir > 0 && BMS_CellVoltTempPage < 4)
            {
                BMS_CellVoltTempPage++; 
                rec =  true;
            }
            if (dir < 0 && BMS_CellVoltTempPage > 1)
            {
                BMS_CellVoltTempPage--; 
                rec =  true;
            }
            if (rec)  writebBMSCellnum();
            return rec;
        }

        byte WriteJsonFileCnt = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {          
            if (WriteJsonFileCnt > 0)
            {
                if (++WriteJsonFileCnt > 5)
                {
                    WriteJSONListToJsonFile(FaultClbJSONFilePath, FaultJsonResults);
                    WriteJsonFileCnt = 0;
                }
            }
            ReadnvmFaultInfoFun(false);
        }
    
        private void button25_Click(object sender, EventArgs e)
        {
            BMS_BMUCellNum = Convert.ToUInt16(textBox98.Text);
            BMS_AfeCellNum = (ushort)(BMS_BMUCellNum / 4);
            setCellVoltInit();
        }
        /// <summary>
        /// 切换PACK编号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btPack1_Click(object sender, EventArgs e)
        {
            BMS_CellVoltTempPage = 1; 
            groupBox2.Text = "PACK "+ BMS_CellVoltTempPage.ToString() + " 单体电芯信息";
            writebBMSCellnum();
        }
        private void btPack2_Click(object sender, EventArgs e)
        {
            BMS_CellVoltTempPage = 2; 
            groupBox2.Text = "PACK " + BMS_CellVoltTempPage.ToString() + " 单体电芯信息";
            writebBMSCellnum();
        }

        private void btPack3_Click(object sender, EventArgs e)
        {
            BMS_CellVoltTempPage = 3;
            groupBox2.Text = "PACK " + BMS_CellVoltTempPage.ToString() + " 单体电芯信息";
            writebBMSCellnum();
        }

        private void btPack4_Click(object sender, EventArgs e)
        {
            BMS_CellVoltTempPage = 4;
            groupBox2.Text = "PACK " + BMS_CellVoltTempPage.ToString() + " 单体电芯信息";
            writebBMSCellnum();
        }

        private void btPack5_Click(object sender, EventArgs e)
        {
            BMS_CellVoltTempPage = 5;
            groupBox2.Text = "PACK " + BMS_CellVoltTempPage.ToString() + " 单体电芯信息";
            writebBMSCellnum();
        }

        private void btPack6_Click(object sender, EventArgs e)
        {
            BMS_CellVoltTempPage = 6;
            groupBox2.Text = "PACK " + BMS_CellVoltTempPage.ToString() + " 单体电芯信息";
            writebBMSCellnum();
        }

        private void btPack7_Click(object sender, EventArgs e)
        {
            BMS_CellVoltTempPage = 7;
            groupBox2.Text = "PACK " + BMS_CellVoltTempPage.ToString() + " 单体电芯信息";
            writebBMSCellnum();
        }
        private void btPack8_Click(object sender, EventArgs e)
        {
            BMS_CellVoltTempPage = 8;
            groupBox2.Text = "PACK " + BMS_CellVoltTempPage.ToString() + " 单体电芯信息";
            writebBMSCellnum();
        }
        /// <summary>
        /// 更新标定阈值CJSON文件 //FactoryJsonResults  FaultJsonResults
        /// </summary>
        /// <param name="FilePath"></param>
        public IList<FaultJsonResult_class> UpLoadFaultClbrCjsonFile(string FilePath ,byte extfarm)
        {
            if (File.Exists(FilePath) == false)
                return null;
            /*
            TreeNode NodeError = new TreeNode();
            TreeNode ErrorCellVol = new TreeNode();
            TreeNode ErrorTemp = new TreeNode();
            TreeNode ErrorOther = new TreeNode();
            */
            StreamReader sR = new StreamReader(FilePath, Encoding.GetEncoding("GB2312"));
            string SearchText = sR.ReadToEnd();
            sR.Close();
            //将 Json 文档解析为 JObject
            JObject Search = JObject.Parse(SearchText);
            //将获得的 Json 结果转换为列表
            try
            {
                IList<JToken> results = Search["FaultClbItem"].Children().ToList();
                //将 Json 结果反序列化为 .NET 对象
                if (extfarm == 0)
                {
                    dataGridView3.Rows.Clear();  
                }
                FaultJsonResults.Clear();
                foreach (JToken result in results)
                {
                    FaultJsonResult_class searchResult = JsonConvert.DeserializeObject<FaultJsonResult_class>(result.ToString());
                    FaultJsonResults.Add(searchResult);
                    if (extfarm == 0)
                    {
                        /*
                        if (searchResult.Comment.Contains("温")) ErrorTemp.Nodes.Add(searchResult.Comment + " : " + searchResult.Val);
                        else if (searchResult.Comment.Contains("压")) ErrorCellVol.Nodes.Add(searchResult.Comment + " : " + searchResult.Val);
                        else ErrorOther.Nodes.Add(searchResult.Comment + " : " + searchResult.Val);
                        */
                        dataGridView3.Rows.Add(searchResult.Comment, searchResult.Val, searchResult.Unit);
                    }    
                }
            }
            catch { }
            return FaultJsonResults;
        }

        /// <summary>
        /// 更新出厂设置CJSON文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="Index"></param>
        void UpLoadFactoryFormulaCjsonFile(string FilePath)
        {
            if (File.Exists(FilePath) == false)
                return;
            StreamReader sR = new StreamReader(FilePath, Encoding.GetEncoding("GB2312"));
            string SearchText = sR.ReadToEnd();
            sR.Close();
            //将 Json 文档解析为 JObject
            JObject Search = JObject.Parse(SearchText);
            //将获得的 Json 结果转换为列表
            try
            {
                IList<JToken> results = Search["FactoryFormula"].Children().ToList();
                //将 Json 结果反序列化为 .NET 对象
                comboBox1.Items.Clear();
                FactoryJsonResults.Clear();
                foreach (JToken result in results)
                {                   
                    FactoryJsonResult_class searchResult = JsonConvert.DeserializeObject<FactoryJsonResult_class>(result.ToString());
                    FactoryJsonResults.Add(searchResult);
                    comboBox1.Items.Add(searchResult.FormulaName);
                } 
            }
            catch { }           
        }

        private void button27_Click(object sender, EventArgs e)
        { 
            UpLoadFactoryFormulaCjsonFile(FactoryJSONFilePath);   
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int Index = comboBox1.SelectedIndex;
            textBox99.Text = FactoryJsonResults[Index].ClusterCellNum;
            textBox100.Text = FactoryJsonResults[Index].AfeCellNum;
            textBox101.Text = FactoryJsonResults[Index].PackNum;
            textBox102.Text = FactoryJsonResults[Index].BMUCellNum;
            textBox103.Text = FactoryJsonResults[Index].BMUAfeNum;
            textBox104.Text = FactoryJsonResults[Index].SWVersion;
            textBox105.Text = FactoryJsonResults[Index].HWVersion;
            textBox106.Text = FactoryJsonResults[Index].SNNum;
            textBox107.Text = "0";
            textBox108.Text = "0";
        }
        //一键设置
        private void button30_Click(object sender, EventArgs e)
        {
            ClbFaultVal myobject = new ClbFaultVal();
            //弹出对话框,
            myobject.ShowDialog(this);//this 必不可少
        }
        //查看更多/标定
        private void button10_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < FaultJsonResults.Count; i++)
            {
                FaultJsonResults[i].Operation = "NULL";
            }
            ClbFaultVal myobject = new ClbFaultVal();
            //弹出对话框,
            myobject.ShowDialog(this);//this 必不可少
        }
        /// <summary>
        /// 标定页面刷新按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button24_Click(object sender, EventArgs e)
        {
            UpLoadFaultClbrCjsonFile(FaultClbJSONFilePath, 0);
        }

        private void button22_Click(object sender, EventArgs e)
        {
            textBox45.Clear();
        }
        /// <summary>
        /// 版本更新,版本校验
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void APPSW_Click(object sender, EventArgs e)
        {

        }

        private void button11_Click(object sender, EventArgs e)
        {
            string strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, (UInt16)CLB_SIGNALNUM.CLB_W_AssignBMUaddr, 1);//
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
        }
        /// <summary>
        /// 删除自身,删除自身所在目录下的所有文件!
        /// </summary>
        /// <param name="args">第一为时间,其他暂无他用</param>
        public void DelselfDir(params int[] args)
        {

            ProcessStartInfo psi = (args.Length <= 0) ? new ProcessStartInfo("cmd.exe", "/C choice /C Y /N /D Y /T 3 & Del " + Application.StartupPath) : new ProcessStartInfo("cmd.exe", string.Format("/C choice /C Y /N /D Y /T {0} & Del " + Application.StartupPath, args[0]))
            {
                UseShellExecute = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true,
            };
            Process.Start(psi);
            Application.Exit();
        }
        /// <summary>
        /// 指定文件夹下面的所有内容copy到目标文件夹下面
        /// 拷贝CodeFilePath目录下的所有文件到指定目录/build/android-ndk-r20b/jni下
        /// </summary>
        /// <param name="srcPath">原始路径</param>
        /// <param name="aimPath">目标文件夹</param>
        /// <returns></returns>
        private static bool CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                {
                    aimPath += Path.DirectorySeparatorChar;
                }
                // 判断目标目录是否存在如果不存在则新建
                if (!Directory.Exists(aimPath))
                {
                    Directory.CreateDirectory(aimPath);
                }
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                // string[] fileList = Directory.GetFiles（srcPath）；
                string[] fileList = Directory.GetFileSystemEntries(srcPath);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    // 先当作目录处理,如果存在这个目录就递归Copy该目录下面的文件
                    if (Directory.Exists(file))
                    {
                        CopyDir(file, aimPath + Path.GetFileName(file));
                    }
                    // 否则直接Copy文件
                    else
                    {
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        /// <summary>
        /// 删除改名字后的文件
        /// </summary>
        void DelChangeAppNameFile()
        {
            string tempPath = System.AppDomain.CurrentDomain.BaseDirectory;
            string[] files = Directory.GetFiles(tempPath);
            foreach (string file in files)
            {
                FileInfo f = new FileInfo(file);
                if (f.Name.Contains("delete"))
                {
                    File.Delete(Path.Combine(tempPath, f.Name));
                }
            }
        }
        void ChangeAppName()
        {
            string filename = Assembly.GetExecutingAssembly().Location;
            File.Move(filename, filename + ".delete");//改名字
        }
        /// <summary>
        /// 解压zip中的文件到目标目录,若文件已存在则删除旧文件,若是exe文件则改名字
        /// </summary>
        void MyZipExraction()
        {
            //解压文件
            DirectoryInfo path = new DirectoryInfo(Application.StartupPath);

            string zipPath = path.Parent.FullName + "/UpdaterDownload.zip";
            string newPath =  System.AppDomain.CurrentDomain.BaseDirectory;
            string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");

            if (File.Exists(zipPath) == false)
                return;
            DirectoryInfo di = new DirectoryInfo(tempPath);
            di.Delete(true);//将文件中的文档删除

            ZipFile.ExtractToDirectory(zipPath, tempPath);

            string[] files = Directory.GetFiles(tempPath);

            foreach (string file in files)
            {
                FileInfo f = new FileInfo(file);
                //Check if the file exists already, if so delete it and then move the new file to the extract folder
                if (File.Exists(Path.Combine(newPath, f.Name)))
                {
                    if (f.Name.Contains("exe"))
                    {
                        ChangeAppName();
                        File.Move(f.FullName, Path.Combine(newPath, f.Name));
                    }
                    else if(f.Name.Contains("dll")|| f.Name.Contains("pdb"))//dll , pdb 格式不改变
                    {
                       
                    }
                    else
                    {
                        File.Delete(Path.Combine(newPath, f.Name));
                        File.Move(f.FullName, Path.Combine(newPath, f.Name));
                    }
                }
                else
                {
                    File.Move(f.FullName, Path.Combine(newPath, f.Name));
                }
            }
            //Delete the temporary directory
            Directory.Delete(tempPath, true);
        }
        void MyAppRestart()
        {
            Application.Exit();
            System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);

        }
        /// <summary>
        /// 测试:解压zip到程序当前目录,删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button12_Click(object sender, EventArgs e)
        { 
            DelChangeAppNameFile();
            MyZipExraction();
            MyAppRestart();
        }

   
        /// <summary>
        /// 上高压
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button13_Click(object sender, EventArgs e)
        {

            textBox45.AppendText("上高压,指令发送成功" + Environment.NewLine);
            string strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, (UInt16)CLB_SIGNALNUM.CLB_W_OpenHightVol, 1);//
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
        }
        /// <summary>
        /// 下高压
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button17_Click(object sender, EventArgs e)
        {
            textBox45.AppendText("下高压,指令发送成功" + Environment.NewLine);
            string strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, (UInt16)CLB_SIGNALNUM.CLB_W_OpenHightVol, 0);//
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
        }
        /// <summary>
        /// 打开绝缘监测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button18_Click(object sender, EventArgs e)
        {
            textBox45.AppendText("打开绝缘检测,指令发送成功" + Environment.NewLine);
            string strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, (UInt16)CLB_SIGNALNUM.CLB_W_IsoDetEnable, 1);//
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
        }
        /// <summary>
        /// 关闭绝缘监测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button19_Click(object sender, EventArgs e)
        {
            textBox45.AppendText("关闭绝缘检查,指令发送成功" + Environment.NewLine);
            string strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, (UInt16)CLB_SIGNALNUM.CLB_W_IsoDetEnable, 0);//
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
        }

        /// <summary>
        /// 从板发送校准指令
        /// </summary>
        void Send_SlaveComm(byte com,uint crcinit)
        {
            if (m_bOpen == 0 || InSlaveMode.SlaveModeAck == 0)//can连接成功,且在从板模式
                return;
            int rand = 0;
            uint CRC32 = 0;
            byte[] buf = new byte[8] { com, 0, 0, 0, 0, 0, 0, 0 };
            Random random = new Random();
            rand = random.Next() & 0x00ffffff;

            if(com == (byte)MyDefine.CANCOM_E.BS_Check_PC)
            {
                buf[1] = (byte)(rand >> 16);
                Send_SlaveCheckcnt = 10;//超时时间1s
                InSlaveMode.SlaveCheckSend = 1;
            }
            if (com == (byte)MyDefine.CANCOM_E.BC_Assignaddr_PC)
            {
                if(string.IsNullOrEmpty(textBox2.Text))
                {
                    textBox2.Text = "1";
                }
                buf[1] = Convert.ToByte(textBox2.Text);
                Send_SlaveAssignaddrcnt = 10;//超时时间1s
                InSlaveMode.SlaveAddrSend = 1;
            }
            buf[2] = (byte)(rand >> 8);
            buf[3] = (byte)rand;

            CRC32 = LibCal_Crc32Multi(buf, 4, crcinit, CRC32_FACTOR);

            buf[4] = (byte)(CRC32 >> 24);
            buf[5] = (byte)(CRC32 >> 16);
            buf[6] = (byte)(CRC32 >> 8);
            buf[7] = (byte)CRC32;
            my_push_send((uint)DBC_ID.INSLAVEMODE, buf, 1);
        }
        /// <summary>
        /// 从板发送校准指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button28_Click(object sender, EventArgs e)
        {  
            Send_SlaveComm((byte)MyDefine.CANCOM_E.BS_Check_PC, (uint)MyDefine.CANCRC32INIT_E.BSI_Check_PC);
        }
        //模拟收到 BMU 握手 / 校验 回复
        unsafe private void label4_Click(object sender, EventArgs e)
        {
            if (comboBox_pcbType.SelectedIndex == 0)
                return;
            byte[] buf = new byte[8] { (byte)MyDefine.CANCOM_E.BS_ShakeHand_BMU, 1, 2, 3, 0, 0, 0, 0 };
            uint CRC32_INIT = (uint)MyDefine.CANCRC32INIT_E.BSI_ShakeHand_BMU;
            uint CRC32 = 0;

            if (InSlaveMode.SlaveModeSend == 1)
            {
                buf[0] = (byte)MyDefine.CANCOM_E.BS_ShakeHand_BMU;
                CRC32_INIT = (uint)MyDefine.CANCRC32INIT_E.BSI_ShakeHand_BMU;
            }
            if (InSlaveMode.SlaveCheckSend == 1)
            {
                buf[0] = (byte)MyDefine.CANCOM_E.BS_Check_BMU;
                CRC32_INIT = (uint)MyDefine.CANCRC32INIT_E.BSI_Check_BMU;
            }
            if (InSlaveMode.SlaveAddrSend == 1)
            {
                buf[0] = (byte)MyDefine.CANCOM_E.BC_Assignaddr_BMU;
                CRC32_INIT = (uint)MyDefine.CANCRC32INIT_E.BCI_Assignaddr_BMU;
            }
            CRC32 = LibCal_Crc32Multi(buf, 4, CRC32_INIT, CRC32_FACTOR);

            buf[4] = (byte)(CRC32 >> 24);
            buf[5] = (byte)(CRC32 >> 16);
            buf[6] = (byte)(CRC32 >> 8);
            buf[7] = (byte)CRC32;

            for (int i = 0; i < 8; i++)
            {
                RecCanData[CircularBuff_rec.head].Data[i] = buf[i];
            }
            RecCanData[CircularBuff_rec.head].ID = (uint)DBC_ID.INSLAVEMODE;
            CircularBuff_rec.head = (ushort)((CircularBuff_rec.head + 1) % RECBUFFSIZE);
            CircularBuff_rec.count = (ushort)(CircularBuff_rec.count + 1);
        }

        private void button29_Click(object sender, EventArgs e)
        {
            Send_SlaveComm((byte)MyDefine.CANCOM_E.BC_Assignaddr_PC, (uint)MyDefine.CANCRC32INIT_E.BCI_Assignaddr_PC);
        }
        /// <summary>
        /// 内容改变需要,检查内容是否合法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox2.Text))
                return;
            foreach (char c in textBox2.Text.ToUpper())
            {
                if (!Regex.IsMatch(c.ToString(), @"[0-9]"))
                {
                    textBox2.Text = "0";
                    return;
                }
            }
            if (Convert.ToInt16(textBox2.Text) > 255) textBox2.Text = "255";
        }
        FaultlogState_s faultlogState_S = new FaultlogState_s();
        void ClearFaultlogMessage(bool tfcard)
        {
            if(tfcard)
            {
                faultlogState_S.tfPackLength = 0;
                faultlogState_S.tfPackCnt = 0;
                faultlogState_S.tfPackCrc32 = 0;
    }
            else
            {
                faultlogState_S.nvmMessageMax = 0;
                faultlogState_S.nvmMessageNub = 0;
                faultlogState_S.nvmMessageCnt = 0;
                faultlogState_S.nvmPackLength = 0;
                faultlogState_S.nvmPackCrc32 = 0;
                faultlogState_S.nvmPackCnt = 0;
            }
        }
        byte my_CRC8(byte[] data,int len) 
        {
            byte temp = data[0];
            for (int i = 1; i < len; i++)
            {
                temp ^= data[i];
            }
            return temp;
        }
        uint faultcrc32init,tempcnt=0;

        /// <summary>
        /// can报文解析,故障日志查询通讯协议
        /// </summary>
        /// <param name="CanID"></param>
        /// <param name="buff"></param>
        void CanFaultlogRecSever(uint CanID,byte[]buff)
        {
            if (CanID == (uint)DBC_ID.FAULTLOG_Single )
            {
                if(faultlogState_S.nvmCheckSend && buff[0] == 0xE3/*&& */)//握手,
                {
                    faultlogState_S.nvmCheckSend = false;
                    if (buff[1] == 4 && my_CRC8(buff, 7) == buff[7])
                    {                    
                        faultlogState_S.nvmCheckAck = true;
                    }
                    else
                    {
                        faultlogState_S.nvmErrorCode = 1;
                    }
                }
                if(faultlogState_S.nvmInfoSend && buff[0] == 0xE1)//信息
                {
                    faultlogState_S.nvmInfoSend = false;
                    if (buff[1] == 4 && my_CRC8(buff, 7) == buff[7])
                    {
                        faultlogState_S.nvmInfoAck = true;
                        ClearFaultlogMessage(false);
                        faultlogState_S.nvmMessageNub = buff[2] << 8 | buff[3];
                        faultlogState_S.nvmMessageMax = buff[4] << 8 | buff[5];
                    }
                    else
                    {
                        faultlogState_S.nvmErrorCode = 2;
                    }
                    
                }
                if (faultlogState_S.tfCheckSend && buff[0] == 0xE5)// TF握手
                {
                    faultlogState_S.tfCheckSend = false;
                    if (buff[1] == 4 && my_CRC8(buff, 7) == buff[7])
                    {                       
                        faultlogState_S.tfCheckAck = true;
                    }
                    else
                    {
                        faultlogState_S.tfErrorCode = 1;

                    }
                }
            }
            if (CanID == (uint)DBC_ID.FAULTLOG_Double )//日志内容
            {
                if(faultlogState_S.nvmMessageSend && buff[0] == faultlogState_S.nvmPackCnt)
                {
                    if (buff[0] == 0)
                    {
                        faultlogState_S.nvmPackCnt = 1;
                        faultlogState_S.nvmPackLength = buff[1] << 16 | buff[2] << 8 | buff[3] ;
                        faultlogState_S.nvmPackCrc32 = buff[4] << 24 | buff[5] << 16 | buff[6] << 8 | buff[7];
                        faultcrc32init = 0x8965;
                    }
                    else if (my_CRC8(buff, 7) == buff[7])
                    {
                        uint temp = (uint)(faultlogState_S.nvmPackLength - (faultlogState_S.nvmPackCnt-1) * 6);
                        if (temp > 6) temp = 6;
                        tempcnt += temp;
                        faultcrc32init = LibCal_Crc32Multi(buff, 1, temp, faultcrc32init, CRC32_FACTOR);
                        if(faultlogState_S.nvmPackCnt*6 >= faultlogState_S.nvmPackLength)
                        {
                            if (faultlogState_S.nvmPackCrc32 != faultcrc32init)
                            {
                                faultlogState_S.nvmErrorCode = 3;
                                faultlogState_S.tfMessageStart = false;
                            }
                            faultlogState_S.nvmMessageSend = false;
                        }
                        faultlogState_S.nvmPackCnt++;
                    }
                    else
                    {
                        faultlogState_S.nvmErrorCode = 2;
                        faultlogState_S.nvmPackCnt = 0;
                        faultlogState_S.nvmMessageSend = false;
                        faultlogState_S.tfMessageStart = false;
                    }
                }
                if (faultlogState_S.tfMessageSend)
                {
                    if (buff[0] == 0)
                    {
                        faultlogState_S.tfPackCnt = 1;
                        faultlogState_S.tfPackLength = buff[1] << 16 | buff[2] << 8 | buff[3];
                        faultlogState_S.tfPackCrc32 = buff[4] << 24 | buff[5] << 16 | buff[6] << 8 | buff[7];
                        faultcrc32init = 0x8965;
                    }
                    else if (my_CRC8(buff, 7) != buff[7])
                    {
                        uint temp = (uint)(faultlogState_S.nvmPackLength - (faultlogState_S.nvmPackCnt - 1) * 6);
                        if (temp > 6) temp = 6;
                        faultcrc32init = LibCal_Crc32Multi(buff, temp, faultcrc32init, CRC32_FACTOR);
                        faultlogState_S.tfPackCnt++;
                        if (faultlogState_S.tfPackCnt >= faultlogState_S.tfPackLength )
                        {
                            if(faultlogState_S.tfPackCrc32 != faultcrc32init)
                            {
                                faultlogState_S.tfErrorCode = 3;
                                faultlogState_S.tfMessageStart = false;
                            }
                            faultlogState_S.tfMessageSend = false;
                        }
                    }  
                    else 
                    {
                        faultlogState_S.tfErrorCode = 2;
                        faultlogState_S.tfPackCnt = 0;
                        faultlogState_S.tfMessageSend = false;
                        faultlogState_S.tfMessageStart = false;
                    }
                }
            }
        }
        /// <summary>
        /// nvm 握手
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void nvmCheck_Click( )
        {
            byte[] buf = new byte[8] { 0xE3, 0, 0, 0, 0, 0, 0, 0 };
            buf[7] = my_CRC8(buf, 7); 
            my_push_send((uint)DBC_ID.FAULTLOG_Single, buf, 1);
            faultlogState_S.nvmCheckSend = true;
            faultlogState_S.nvmCheckAck = false;
        }
        /// <summary>
        /// 获取nvm中故障日志数量信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReadnvmFaultloginfo_Click( )
        {
            if(faultlogState_S.nvmCheckAck == false)  
                return; 
            byte[] buf = new byte[8] { 0xE1, 0, 0, 0, 0, 0, 0, 0 }; 
            buf[7] = my_CRC8(buf, 7);
            my_push_send((uint)DBC_ID.FAULTLOG_Single, buf, 1);
            faultlogState_S.nvmInfoSend = true;
            faultlogState_S.nvmInfoAck = false;
        }
        /// <summary>
        /// 一次读一个日志,放在定时器中
        /// </summary>
        void ReadnvmFaultInfoFun( bool tfcard)
        {
            if(tfcard)
            {
                if (faultlogState_S.tfMessageStart == false || faultlogState_S.tfCheckAck == false)
                    return;
                byte[] buf = new byte[8] { 0xE6, 0, 0, 0, 0, 0, 0, 0 };
                faultlogState_S.tfTimeStamp = 1234500;
                buf[1] = (byte)(faultlogState_S.tfTimeStamp >> 24);
                buf[2] = (byte)(faultlogState_S.tfTimeStamp >> 16);
                buf[3] = (byte)(faultlogState_S.tfTimeStamp >> 8);
                buf[4] = (byte)faultlogState_S.tfTimeStamp;
                buf[5] = 0;
                buf[6] = 20; 
                buf[7] = my_CRC8(buf, 7);
                my_push_send((uint)DBC_ID.FAULTLOG_Single, buf, 1);
                faultlogState_S.tfMessageSend = true;   
            }
            else
            {
                if (faultlogState_S.nvmMessageStart == false || 
                    faultlogState_S.nvmCheckAck == false || 
                    faultlogState_S.nvmMessageSend )
                    return;
                if (++faultlogState_S.nvmMessageCnt > faultlogState_S.nvmMessageMax)
                {
                    faultlogState_S.nvmMessageStart = false;
                }
                else
                {
                    byte[] buf = new byte[8] { 0xE2, 0, 0, 0, 0, 0, 0, 0 };
                    int temp = 0;
                    if (faultlogState_S.nvmMessageNub >= faultlogState_S.nvmMessageCnt - 1)
                         temp = faultlogState_S.nvmMessageNub - (faultlogState_S.nvmMessageCnt - 1);
                    else
                        temp = faultlogState_S.nvmMessageMax  - (faultlogState_S.nvmMessageCnt - 1 - faultlogState_S.nvmMessageNub);
                    buf[1] = (byte)(temp >> 24);
                    buf[2] = (byte)(temp >> 16);
                    buf[3] = (byte)(temp >> 8);
                    buf[4] = (byte)temp;
                    buf[5] = 0;
                    buf[6] = 1;
                    buf[7] = my_CRC8(buf, 7);
                    my_push_send((uint)DBC_ID.FAULTLOG_Single, buf, 1);
                    faultlogState_S.nvmMessageSend = true;
                }
            }
        }
        /// <summary>
        /// 读出NVM所有故障日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReadAllFaultLog_Click( )
        {
            if (faultlogState_S.nvmCheckAck == false || faultlogState_S.nvmMessageMax == 0)
                return; 
            faultlogState_S.nvmMessageStart = true;
            faultlogState_S.nvmMessageCnt = 0;
            faultlogState_S.nvmPackCnt = 0;
            faultlogState_S.nvmMessageSend = false;
        }

        /// <summary>
        /// TF卡故障日志握手
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tfCheck_Click( )
        {
            byte[] buf = new byte[8] { 0xE5, 0, 0, 0, 0, 0, 0, 0 }; 
            buf[7] = my_CRC8(buf, 7);
            my_push_send((uint)DBC_ID.FAULTLOG_Single, buf, 1);
            faultlogState_S.tfCheckSend = true;
            faultlogState_S.tfCheckAck = false;          
        }

        /// <summary>
        /// TF卡 :根据时间戳,获取时间段的工作日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReadtfWorklogINFO_Click()
        {
            if (faultlogState_S.tfCheckAck == false)
                return;
            ReadnvmFaultInfoFun(true);
            ClearFaultlogMessage(true);
            faultlogState_S.tfMessageStart = true;
        }
        //json  转 DataTable
        public DataTable ToDataTableTwo(string json)
        {
            DataTable dataTable = new DataTable(); //实例化
            DataTable result;
            try
            {
                JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
                ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
                if (arrayList.Count > 0)
                {
                    foreach (Dictionary<string, object> dictionary in arrayList)
                    {
                        if (dictionary.Keys.Count<string>() == 0)
                        {
                            result = dataTable;
                            return result;
                        }
                        //Columns
                        if (dataTable.Columns.Count == 0)
                        {
                            foreach (string current in dictionary.Keys)
                            {
                                dataTable.Columns.Add(current, dictionary[current].GetType());
                            }
                        }
                        //Rows
                        DataRow dataRow = dataTable.NewRow();
                        foreach (string current in dictionary.Keys)
                        {
                            dataRow[current] = dictionary[current];
                        }
                        dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                        //Console.WriteLine(dataTable.Rows[0].ToString());
                    }
                }
            }
            catch
            {
            }
            result = dataTable;
            return result;
        }
        //导出Excel
        public void dataTableToCsv(DataTable table, string file)
        {
            string title = "";
            FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
            for (int i = 0; i < table.Columns.Count; i++)
            {
                //Console.WriteLine(table.Columns[i].ColumnName);
                //title += table.Columns[i].ColumnName + "\t"; //栏位：自动跳到下一单元格
                title += table.Columns[i].ColumnName + "\t"; //栏位：自动跳到下一单元格
            }

            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);
            foreach (DataRow row in table.Rows)
            {
                string line = "";
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    line += row[i].ToString().Trim() + "\t"; //内容：自动跳到下一单元格
                }
                line = line.Substring(0, line.Length - 1) + "\n";
                sw.Write(line);
            }
            sw.Close();
            fs.Close();
        }
        //json  转 DataTable  类型   然后导出  excel
        //参数1 String json json数据 参数2 tabName导出成Excel后的名称
        public String jsonToDataTable(String json, String tabName)
        {
            String meg = "fail";
            //System.Windows.Forms.MessageBox.Show(json);
            //json数据转成  DataTable   类型
            DataTable dataTab = ToDataTableTwo(json);
            //调用另存为  系统文件窗口
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            //设置文件类型
            saveFileDialog.FileName = tabName;  //导出excel的默认名称
            saveFileDialog.Filter = "Excel files(*.xls)|*.xls";
            //保存对话框是否记忆上次打开的目录
            saveFileDialog.RestoreDirectory = true;
            //String DialogResult = saveFileDialog.ShowDialog();
            //点了保存按钮进入
            if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //获得文件路径
                String localFilePath = saveFileDialog.FileName.ToString();
                //System.Windows.Forms.MessageBox.Show(localFilePath);
                dataTableToCsv(dataTab, localFilePath);
                meg = "success";
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("导出失败");
            }
            return meg;
        }
        /// <summary>
        /// 将TF卡中的文件导出至execl
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void jsonoutputexecl()
        {
            string jsonstr = JsonConvert.SerializeObject(FaultJsonResults, Formatting.Indented);
            jsonToDataTable(jsonstr, faultlogState_S.tfTimeStamp.ToString());
        }
        /// <summary>
        /// 握手bmu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button35_Click(object sender, EventArgs e)
        {
            if(m_bOpen == 1 && comboBox_pcbType.SelectedIndex == 1)
            {
                InSlaveMode.SlaveModeStart = 1;
            }
        }

        private void tabControl11_SelectedIndexChanged(object sender, IntEventArgs e)
        {
            NowTabConSelectedIndex = (byte)tabControl11.SelectedIndex;
        }
        private void button4_Click_1(object sender, EventArgs e)
        {
            nvmCheck_Click();
        }

        private void button38_Click(object sender, EventArgs e) 
        {
            ReadnvmFaultloginfo_Click();
        }

        private void button39_Click(object sender, EventArgs e)
        {
            ReadAllFaultLog_Click();
        }
        void BmuBootLogAppText(string str,bool time)
        {
            if (time) str = DateTime.Now.ToString("T") + " " + str;
            input_log.AppendText(str);
            input_log.ScrollToEnd();
        }
        void BcuBootLogAppText(string str, bool time)
        {
            if (time) str = DateTime.Now.ToString("T") + " " + str;
            input6.AppendText(str);
            input6.ScrollToEnd();
        }
        /// <summary>
        /// boot 固件升级 回包
        /// </summary>
        /// <param name="CanID"></param>
        /// <param name="arry"></param>
        void CanBootRecAck(uint CanID, byte[] arry)
        {

            if (CanID == DevBootData[DevAddr].CmdID )                 
            {
                if (arry[1] == 1|| arry[3] == 1 || arry[1] == 5)
                {
                    DevBootData[DevAddr].Ack = 1;
                }
                if (arry[1] == 6)
                {
                    DevBootData[DevAddr].ErrorCnt++;
                }
                if (arry[1] == 2)
                {                 
                    if (DevBootData[DevAddr].State > MyDefine.BootState_E.BS_NULL)
                        DevBootData[DevAddr].State = MyDefine.BootState_E.BS_FAIL;
                    if (DevAddr == 8) input6.AppendText("\r\n " + DateTime.Now.ToString("T") + "  Flash error!\r\n");
                    else input_log.AppendText("\r\n " + DateTime.Now.ToString("T") + "  Flash error!\r\n");
                }
                if (arry[1] == 3)
                {
                    if (DevBootData[DevAddr].State > MyDefine.BootState_E.BS_NULL)
                        DevBootData[DevAddr].State = MyDefine.BootState_E.BS_FAIL;
                    if (DevAddr == 8) input6.AppendText("\r\n " + DateTime.Now.ToString("T") + "  File error!\r\n");
                    else input_log.AppendText("\r\n " + DateTime.Now.ToString("T") + "  File error!\r\n");
                }
                if (arry[1] == 4)
                {
                    if (DevBootData[DevAddr].State > MyDefine.BootState_E.BS_NULL)
                        DevBootData[DevAddr].State = MyDefine.BootState_E.BS_FAIL;
                    if (DevAddr == 8) input6.AppendText("\r\n " + DateTime.Now.ToString("T") + "  Error during update!\r\n");
                    else input_log.AppendText("\r\n " + DateTime.Now.ToString("T") + "  Error during update!\r\n");
                }                                    
            }
            if (CanID == DevBootData[DevAddr].DataID )
            {
                if(arry[3] > 1 && arry[3] < 5)
                    DevBootData[DevAddr].OutTime += BootCanOutTime;
                else 
                    DevBootData[DevAddr].Ack = 1;
            }
            
        }
        /// <summary>
        /// can发送指令,并判断回包
        /// </summary>
        /// <param name="DBootD">DBootD</param>
        /// <param name="buf">buf</param>
        /// <param name="outtime">超时时间</param>
        /// <param name="outtimecnt">超时次数</param>
        /// <returns>BOOTDATA_s</returns>
        MyDefine.BOOTDATA_s BOOTCanAck(MyDefine.BOOTDATA_s DBootD, byte[] buf, UInt16 outtime, UInt16 outtimecnt,string log)
        {

            if (DBootD.OutTime == 0)
            {                
                DBootD.OutTime = 1;
                DBootD.Ack = 0;
                DBootD.Order = buf[0];
                my_push_send(DBootD.CmdID, buf, 1);
                if (DevAddr == 8) BcuBootLogAppText(log,true);
                else
                {
                    BmuBootLogAppText(log,true);
                }
            }
            else
            {
                //bms回包
                if (DBootD.Ack == 1)
                {
                    clear_fifo_send();
                    DBootD.Ack = 0;
                    DBootD.OutTime = 0;
                    DBootD.ErrorCnt = 0;
                    if(DevAddr == 8) input6.AppendText("成功\r\n");
                    else input_log.AppendText("成功\r\n");
                    if (DBootD.State == MyDefine.BootState_E.BS_CHECKBIN)
                    {
                        //增加,判断是否校验成功
                        DBootD.State = MyDefine.BootState_E.BS_SUCCEED;
                    }
                    else
                    {                       
                        DBootD.State++;
                    }
                }
                //回包超时
                if (DBootD.OutTime > outtime)
                {
                    DBootD.OutTime = 0;
                    //判断超时次数
                    if (++DBootD.ErrorCnt > outtimecnt)
                    {
                        DBootD.Ack = 0;
                        DBootD.ErrorCnt = 0;
                        DBootD.State = MyDefine.BootState_E.BS_FAIL;
                        if (DevAddr == 8) BmuBootLogAppText("\r\nBMS回包超时\r\n",false);
                        else BmuBootLogAppText("\r\nBMS回包超时\r\n", false);
                    }
                }
            }
            return DBootD;
        }
        public bool BmuBootStateCheckCmdfun(CAN_ID_DATA sendobj)
        {
            if(sendobj.strbuff == null) 
                return false;
            string[] sArray = sendobj.strbuff.Split(' ');
            byte bootcmd = Convert.ToByte("0x" + sArray[0], 16);
            if (sendobj.ID == DevBootData[DevAddr].CmdID)
            {
                if (DevBootData[DevAddr].State == MyDefine.BootState_E.BS_START)
                {
                    if(bootcmd != 0xE1) return false;
                }
                if (DevBootData[DevAddr].State == MyDefine.BootState_E.BS_FileSize)
                {
                    if(bootcmd != 0xE2) return false;
                }
                if (DevBootData[DevAddr].State == MyDefine.BootState_E.BS_Erasechip)
                {
                    if(bootcmd != 0xE6) return false;
                }
            }
            return true;
        }
        void InSilentMode(byte i)
        {           
           
            if (DevBootData[i].OutTime%2 == 0)
            {
                bmuInSilentMode();
            }
            if (++DevBootData[i].OutTime > 10)
            {
                DevBootData[i].OutTime = 0;
                DevBootData[i].State = MyDefine.BootState_E.BS_SILENT;
                UpdataBmuBootTimeSpan(i, true);
            }
        }
        /// <summary>
        /// 50ms/次发送指令,30次,未回复超时失败,回复进入下一个模式
        /// </summary>
        /// <param name="i"></param>
        /// <param name="buf"></param>
        void EnterBootMode(byte i, byte[] buf)
        {
            if (DevBootData[i].Ack == 1)
            {
                clear_fifo_send();
                clear_fifo_rec();
                if (i == 8)input6.AppendText("成功\r\n");
                else input_log.AppendText("成功\r\n");
                DevBootData[i].Ack = 0;
                DevBootData[i].OutTime = 0;
                DevBootData[i].ErrorCnt = 0;
                DevBootData[i].State++;
                return;
            }
            if (DevBootData[i].OutTime == 0)
            {
                clear_fifo_send();
                clear_fifo_rec();
                DevBootData[i].OutTime++;
                if (i == 8) BcuBootLogAppText((i + 1).ToString() + " 号固件开始升级,信息握手;",true);
                else BmuBootLogAppText((i + 1).ToString() + " 号固件开始升级,信息握手;",true);
            }
            DevBootData[i].Order = buf[0];
            my_push_send(DevBootData[i].CmdID, buf, 1);
            //回包超时
            if (DevBootData[i].OutTime > 40)
            {
                DevBootData[i].OutTime = 0;
                DevBootData[i].Ack = 0;
                DevBootData[i].ErrorCnt = 0;
                DevBootData[i].State = MyDefine.BootState_E.BS_FAIL;
                if(i == 8)
                {
                    BcuBootLogAppText("\r\nBMS回包超时\r\n",false);
                }
                else
                {
                    BmuBootLogAppText("\r\nBMS回包超时\r\n", false);
                }
                
            }  
        }
        void setBMUprogressValue(byte i)
        {
            if (i == 0)
            {
                progress_bmu1.Value = DevBootData[i].progress;
                progress_bmu1.State = TType.None;
            }
            if (i == 1)
            {
                progress_bmu2.Value = DevBootData[i].progress;
                progress_bmu2.State = TType.None;
            }
            if (i == 2)
            {
                progress_bmu3.Value = DevBootData[i].progress;
                progress_bmu3.State = TType.None;
            }
            if (i == 3)
            {
                progress_bmu4.Value = DevBootData[i].progress;
                progress_bmu4.State = TType.None;
            }
            if (i == 4)
            {
                progress_bmu5.Value = DevBootData[i].progress;
                progress_bmu5.State = TType.None;
            }
            if (i == 5)
            {
                progress_bmu6.Value = DevBootData[i].progress;
                progress_bmu6.State = TType.None;
            }
            if (i == 6)
            {
                progress_bmu7.Value = DevBootData[i].progress;
                progress_bmu7.State = TType.None;
            }
            if (i == 7)
            {
                progress_bmu8.Value = DevBootData[i].progress;
                progress_bmu8.State = TType.None;
            }
            if (i == 8)
            {
                progress8.Value = DevBootData[i].progress;
                progress8.State = TType.None;
            }
        }
        void setBMUprogressState(byte i,AntdUI.TType state)
        {
            if (i == 0) progress_bmu1.State = state;
            if (i == 1) progress_bmu2.State = state;
            if (i == 2) progress_bmu3.State = state;
            if (i == 3) progress_bmu4.State = state;
            if (i == 4) progress_bmu5.State = state;
            if (i == 5) progress_bmu6.State = state;
            if (i == 6) progress_bmu7.State = state;
            if (i == 7) progress_bmu8.State = state;
        }
        byte BootCanOutTime = 20, BootCanOutTimeCnt = 5;
        int SingleBootCnt = 0, SingleBootErrorCnt = 0;
        bool bmuSingleBoot = false;
        void BootLoaderServe( byte i)
        {
            bool DevBootStart = false;

            /* bmu 自动测试脚本,压力测试,测试次数100,错误10次后停止测试*/
            if (DevBootData[i].State == MyDefine.BootState_E.BS_NULL && bmuSingleBoot) 
            {
                UpdataBmuBootTimeSpan(i, true);
                DevBootData[i].OutTime = 0;
                DevBootData[i].State = MyDefine.BootState_E.BS_SILENT;
                if (++SingleBootCnt >= 100)
                {
                    bmuSingleBoot = false;  
                }
                lbAutoTest.Text = SingleBootErrorCnt.ToString() + "/" + SingleBootCnt.ToString();
            }
            if (bmuAutoBoot && DevBootData[i].State == MyDefine.BootState_E.BS_NULL)
            {
                InSilentMode(i);
                return;
            }
            if (DevBootData[i].State > MyDefine.BootState_E.BS_NULL)
            {
                DevBootStart = true;
            }
            
            if (DevBootStart)
            {
                if (DevBootData[i].OutTime > 0) DevBootData[i].OutTime++;
                byte[] buf = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
                string str = " ";
                switch (DevBootData[i].State)
                {                         
                    case MyDefine.BootState_E.BS_FAIL://失败 
                        clear_fifo_send();
                        DevBootData[i].State = MyDefine.BootState_E.BS_NULL;
                        SingleBootErrorCnt++;
                        setBMUprogressState(i, TType.Error);
                        if(i == 8)  BcuBootLogAppText((i + 1).ToString() + " 号固件升级失败\r\n", true); 
                        else BmuBootLogAppText((i + 1).ToString() + " 号固件升级失败\r\n", true);
                        AutoTest1to8();
                        break;
                    case MyDefine.BootState_E.BS_SUCCEED://成功                         
                        DevBootData[i].State = MyDefine.BootState_E.BS_NULL;
                        DevBootData[i].progress = 1;
                        long val = UpdataBmuBootTimeSpan(i, false);
                        setBMUprogressValue(i);
                        setBMUprogressState(i, TType.Success);
                        if (i == 8) BcuBootLogAppText((i + 1).ToString() + " 号固件升级成功,耗时,"+ val.ToString() + "秒\r\n", true);
                        else BmuBootLogAppText((i + 1).ToString() + " 号固件升级成功,耗时,"+ val.ToString() + "秒\r\n", true);
                        AutoTest1to8();
                        break;
                    case MyDefine.BootState_E.BS_SILENT:
                        bmuInSilentMode();
                        DevBootData[i].State = MyDefine.BootState_E.BS_START;
                        break;
                    case MyDefine.BootState_E.BS_START://开始 
                        buf[0] = 0xE1;
                        buf[1] = DevBootData[i].FirmwareType;
                        buf[2] = DevBootData[i].FirmwareVersion;
                        Random random = new Random();
                        long rand = random.Next() & 0xffffffff;
                        buf[3] = (byte)(rand >> 24);
                        buf[4] = (byte)(rand >> 16);
                        buf[5] = (byte)(rand >> 8);
                        buf[6] = (byte)rand;
                        buf[7] = (byte)(buf[0] ^ buf[1] ^ buf[2] ^ buf[3] ^ buf[4] ^ buf[5] ^ buf[6]);
                        EnterBootMode(i, buf);
                        DevBootData[i].progress = 0.02f;
                        setBMUprogressValue(i);
                        break;
                    case MyDefine.BootState_E.BS_FileSize://发送固件大小 
                        str = "确认固件大小和CRC;";
                        buf[0] = 0xE2;
                        buf[1] = (byte)(DevBootData[i].FirmwareSize >> 16);
                        buf[2] = (byte)(DevBootData[i].FirmwareSize >> 8);
                        buf[3] = (byte)(DevBootData[i].FirmwareSize);
                        buf[4] = (byte)(DevBootData[i].CrcSize >> 24);
                        buf[5] = (byte)(DevBootData[i].CrcSize >> 16);
                        buf[6] = (byte)(DevBootData[i].CrcSize >> 8);
                        buf[7] = (byte)(DevBootData[i].CrcSize);
                        DevBootData[i] = BOOTCanAck(DevBootData[i], buf, BootCanOutTime, BootCanOutTimeCnt, str);
                        DevBootData[i].progress = 0.04f;
                        setBMUprogressValue(i);
                        break;
                    case MyDefine.BootState_E.BS_Erasechip://擦除 
                        str = "BMS擦除固件FLASH;";
                        buf[0] = 0xE6;
                        DevBootData[i].PageIndex = 0;
                        DevBootData[i].SendDataStep = 0;
                        DevBootData[i] = BOOTCanAck(DevBootData[i], buf, (ushort)(BootCanOutTime + 60), BootCanOutTimeCnt, str);
                        DevBootData[i].progress = 0.08f;
                        setBMUprogressValue(i);
                        break;
                    case MyDefine.BootState_E.BS_SANDBIN://发送固件 
                        Boot_SandBinFile(i);
                        break;
                    case MyDefine.BootState_E.BS_CHECKBIN://校验固件 
                        str = "固件校验";
                        buf[0] = 0xE5;
                        DevBootData[i] = BOOTCanAck(DevBootData[i], buf, BootCanOutTime, BootCanOutTimeCnt, str);
                        DevBootData[i].progress = 0.98f;
                        setBMUprogressValue(i);
                        break;
                }
            }
        }
        byte[] BinDataBuffer = new byte[518];
        byte BinPageEndbyte = 0;
        void UpdataBinDataBuffer(byte i)
        {
            uint pagecnt = 0, read_data_num = 0;
            string strpath = input_bootfilepath.Text;
            if (i == 8) strpath = input5.Text;
            if (File.Exists(strpath) == false)
            {
                if (i == 8) input6.AppendText("\r\nBin文件加载失败\r\n");
                else input_log.AppendText("\r\nBin文件加载失败\r\n");
                return;
            }
            BinaryReader br = new BinaryReader(new FileStream(strpath, FileMode.Open));
            while (pagecnt++ <= DevBootData[i].PageIndex)
            {
                BinPageEndbyte = 0;
                Array.Clear(BinDataBuffer, 0, 518);
                read_data_num = (UInt16)br.Read(BinDataBuffer, 0, 512);
            }
            br.Close();
            DevBootData[i].CrcPage = LibCal_Crc32Multi(BinDataBuffer, 512, 0, CRC32_FACTOR);
        }
        long UpdataBmuBootTimeSpan(byte i,bool start)
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            if (start)
                DevBootData[i].TimeSpanStart = Convert.ToInt64(ts.TotalSeconds);
            else
                DevBootData[i].TimeSpanOpt = Convert.ToInt64(ts.TotalSeconds);
            return DevBootData[i].TimeSpanOpt - DevBootData[i].TimeSpanStart;
        }
        /// <summary>
        /// 发送bin文件
        /// </summary>
        /// <param name="i"></param>
        void Boot_SandBinFile(byte i)
        {
            byte[] buf = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
            if ( DevBootData[i].SendDataStep >= 75)//发送最后一帧 需要等待回包 ; 7*74=518 ; 
            {                
                if (DevBootData[i].OutTime == 0)
                {
                    DevBootData[i].OutTime = 1;
                    DevBootData[i].Ack = 0;
                    DevBootData[i].Order = 0;
                    clear_fifo_send();
                    buf[0] = 0x49;
                    buf[1] = BinPageEndbyte;
                    my_push_send(DevBootData[i].DataID, buf, 1);
                }
                else
                {
                    if (DevBootData[i].Ack == 1)
                    {
                        clear_fifo_send();
                        DevBootData[i].Ack = 0;
                        DevBootData[i].OutTime = 0;
                        DevBootData[i].ErrorCnt = 0;
                        DevBootData[i].SendDataStep = 0;
                        DevBootData[i].PageIndex++;
                        if (DevBootData[i].progress < 0.97f)
                        {
                            DevBootData[i].progress += 0.01f;
                            setBMUprogressValue(i);
                        }
                        if (DevBootData[i].PageIndex * 512 >= DevBootData[i].FirmwareSize)
                        {
                            DevBootData[i].State++;
                            return;
                        }            
                    }

                    if (DevBootData[i].OutTime > BootCanOutTime)
                    {
                        //超时1次后:
                        /*方式1:当页重新发*/
                        //DevBootData[i].OutTime = 0;
                        //DevBootData[i].SendDataStep = 0;
                        /*方式2:当页的最后1帧重新发,*/
                        DevBootData[i].OutTime = 0;
                        
                        if (++DevBootData[i].ErrorCnt > BootCanOutTimeCnt)
                        {
                            DevBootData[i].Ack = 0;
                            DevBootData[i].ErrorCnt = 0;
                            DevBootData[i].SendDataStep = 0;
                            DevBootData[i].State = MyDefine.BootState_E.BS_FAIL;
                            if (i == 8) BcuBootLogAppText("BMS回包超时\r\n", false);
                            else BmuBootLogAppText("BMS回包超时\r\n", false);
                        }
                    }
                }
            }
            else if(DevBootData[i].SendDataStep > 0)//发送数据 512byte 不需要回包
            {
                if (DevBootData[i].SendDataStep == 1)
                {
                    if (i == 8) BcuBootLogAppText("发送中...", false);
                    else BmuBootLogAppText("发送中...", false);
                }
                DevBootData[i].OutTime = 0;
                DevBootData[i].ErrorCnt = 0;
                while (true)
                {
                    buf[0] = (byte)(DevBootData[i].SendDataStep - 1);
                    DevBootData[i].Order = 0;
                    Array.Copy(BinDataBuffer, buf[0] * 7, buf, 1, 7);
                    my_push_send(DevBootData[i].DataID, buf, 1);
                    if (++DevBootData[i].SendDataStep == 75)
                    {
                        DevBootData[i].OutTime = 1;
                        DevBootData[i].Ack = 0;
                        if (i == 8) BcuBootLogAppText(" ; 发送完成.\r\n",false);
                        else BmuBootLogAppText(" ; 发送完成.\r\n",false);
                        if ((DevBootData[i].PageIndex + 1) * 512 >= DevBootData[i].FirmwareSize)
                        {
                            long val = UpdataBmuBootTimeSpan(i, false);
                            if (i == 8) BcuBootLogAppText("固件发送完成,固件大小:" + DevBootData[i].FirmwareSize.ToString() + "Byte ,耗时:" + val.ToString() + "秒\r\n", true);
                            else BmuBootLogAppText("固件发送完成,固件大小:" + DevBootData[i].FirmwareSize.ToString() + "Byte ,耗时:" + val.ToString() + "秒\r\n", true);
                        }
                        break;
                    }
                }
            }
            if (DevBootData[i].SendDataStep == 0)//发送页码 
            {
                if (DevBootData[i].OutTime == 0)
                {
                    clear_fifo_send();
                    DevBootData[i].CrcPage = 0;
                    UpdataBinDataBuffer(i);
                    buf[0] = 0xE4;
                    buf[1] = (byte)(DevBootData[i].PageIndex >> 16);
                    buf[2] = (byte)(DevBootData[i].PageIndex >> 8);
                    buf[3] = (byte)(DevBootData[i].PageIndex);
                    buf[4] = (byte)(DevBootData[i].CrcPage >> 24);
                    buf[5] = (byte)(DevBootData[i].CrcPage >> 16);
                    buf[6] = (byte)(DevBootData[i].CrcPage >> 8);
                    buf[7] = (byte)(DevBootData[i].CrcPage);
                    DevBootData[i].Ack = 0;
                    DevBootData[i].OutTime = 1;
                    DevBootData[i].Order = buf[0];
                    my_push_send(DevBootData[i].CmdID, buf, 1);
                    if (i == 8) BcuBootLogAppText("第 " + DevBootData[i].PageIndex.ToString() + " 页",true);
                    else BmuBootLogAppText("第 " + DevBootData[i].PageIndex.ToString() + " 页", true);
                }
                else
                {
                    if (DevBootData[i].Ack == 1)
                    {
                        clear_fifo_send();
                        DevBootData[i].Ack = 0;
                        DevBootData[i].OutTime = 0;
                        DevBootData[i].ErrorCnt = 0;
                        DevBootData[i].SendDataStep++;
                    }
                    if (DevBootData[i].OutTime > BootCanOutTime)
                    {
                        DevBootData[i].OutTime = 0;
                        if (++DevBootData[i].ErrorCnt > BootCanOutTimeCnt)
                        {
                            DevBootData[i].Ack = 0;
                            DevBootData[i].ErrorCnt = 0;
                            DevBootData[i].State = MyDefine.BootState_E.BS_FAIL;
                            if (i == 8) BcuBootLogAppText("BMS回包超时\r\n",false);
                            BmuBootLogAppText("BMS回包超时\r\n",false);
                        }
                    }
                }
            }
        }
        void bmuInSilentMode()
        {
            byte[] buf = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
            Random random = new Random();
            long rand = random.Next() & 0xffffffff;
            buf[0] = (byte)(rand >> 24);
            buf[1] = (byte)(rand >> 16);
            buf[2] = (byte)(rand >> 8);
            buf[3] = (byte)rand;
            uint crc32temp = LibCal_Crc32Multi(buf, 4, 0, CRC32_FACTOR);
            buf[4] = (byte)(crc32temp >> 24);
            buf[5] = (byte)(crc32temp >> 16);
            buf[6] = (byte)(crc32temp >> 8);
            buf[7] = (byte)crc32temp;
            my_push_send(0x7d6, buf, 4);//使bmu进入静默模式
        }
        private void btClear_Click(object sender, EventArgs e)
        {
            //BoxText_str = "固件升级成功";
            //BoxColor_str = Color.Green;
            //BoxText_str = "固件升级失败";
            //BoxColor_str = Color.Red;
            //faultlogState_S.nvmErrorCode = 0;
            //MyMessageBox mmb = new MyMessageBox();
            //mmb.ShowDialog(this);//this 必不可少 
            input_log.Clear();          
        }
        private void btAddFile_Click(object sender, EventArgs e)
        {
            uint crc32temp = 0;
            byte[] DataBuffer = new byte[512];
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "二进制文件(*.bin)|*.bin";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                timer_boot.Enabled = true;
                button4.Enabled = true;
                input_bootfilepath.Text = fd.FileName;
                if (File.Exists(input_bootfilepath.Text) == false)
                {
                    input_log.AppendText("\r\nBin文件加载失败\r\n");
                    return;
                }
                bmuInSilentMode();
                uint temp = (uint)new FileInfo(input_bootfilepath.Text).Length;
                BmuBootLogAppText("固件加载成功,固件大小:" + temp .ToString()+ "byte\r\n", true);
                BinaryReader br = new BinaryReader(new FileStream(input_bootfilepath.Text, FileMode.Open));
                for (UInt32 AddrOffset = 0; AddrOffset < temp;)
                {
                    UInt16 read_data_num = (UInt16)br.Read(DataBuffer, 0, 512);
                    crc32temp = LibCal_Crc32Multi(DataBuffer, read_data_num, crc32temp, CRC32_FACTOR);
                    AddrOffset += read_data_num;
                }
                br.Close();
                for (byte i = 0; i < 8; i++)
                {
                    DevBootData[i].FirmwareType = 1;
                    DevBootData[i].FirmwareSize = temp;
                    DevBootData[i].CrcSize = crc32temp;
                    DevBootData[i].FirmwareVersion = 100;
                    DevBootData[i].State = MyDefine.BootState_E.BS_NULL;
                    DevBootData[i].progress = 0;
                    setBMUprogressValue(i);
                }
                clear_fifo_rec();
                DevBootData[0].CmdID = 0x7A8;
                DevBootData[0].DataID = 0x7A9;
                DevBootData[1].CmdID = 0x7AC;
                DevBootData[1].DataID = 0x7AD;
                DevBootData[2].CmdID = 0x7B0;
                DevBootData[2].DataID = 0x7B1;
                DevBootData[3].CmdID = 0x7B4;
                DevBootData[3].DataID = 0x7B5;
                DevBootData[4].CmdID = 0x7B8;
                DevBootData[4].DataID = 0x7B9;
                DevBootData[5].CmdID = 0x7BC;
                DevBootData[5].DataID = 0x7BD;
                DevBootData[6].CmdID = 0x7C0;
                DevBootData[6].DataID = 0x7C1;
                DevBootData[7].CmdID = 0x7C4;
                DevBootData[7].DataID = 0x7C5;
                btStartBoot_bmu1.Enabled = true;
                btStartBoot_bmu2.Enabled = true;
                btStartBoot_bmu3.Enabled = true;
                btStartBoot_bmu4.Enabled = true;
                btStartBoot_bmu5.Enabled = true;
                btStartBoot_bmu6.Enabled = true;
                btStartBoot_bmu7.Enabled = true;
                btStartBoot_bmu8.Enabled = true;
                button31.Enabled = true;
                button32.Enabled = true;
            }
            else
            {
                btStartBoot_bmu1.Enabled = false;
                btStartBoot_bmu2.Enabled = false;
                btStartBoot_bmu3.Enabled = false;
                btStartBoot_bmu4.Enabled = false;
                btStartBoot_bmu5.Enabled = false;
                btStartBoot_bmu6.Enabled = false;
                btStartBoot_bmu7.Enabled = false;
                btStartBoot_bmu8.Enabled = false;
                button31.Enabled = false;
                button32.Enabled = false;
                BmuBootLogAppText("固件加载失败\r\n", false);
            }
        }

        private void timer_boot_Tick(object sender, EventArgs e)
        { 
            BootLoaderServe(DevAddr);
        }
        bool checkbootstatefun()
        {
            if (m_bOpen == 0)
            {
                BmuBootLogAppText("\r\n请在设备页面连接串口\r\n", false);
                return false;
            }
            if (comboBox_pcbType.SelectedIndex == 0)
            {
                BmuBootLogAppText("\r\n请在设备页面选择单板采集模式\r\n", false);
                return false;
            }
            for (byte i = 0; i < 8; i++)
            {
                if (DevBootData[i].State >= MyDefine.BootState_E.BS_SILENT)
                {
                    BmuBootLogAppText("\r\n固件升级中,请勿重复操作\r\n", false);
                    return false;
                }
            }
            return true;
        }
        byte DevAddr = 0;
        void DevBootDataStartInit(byte i)
        {
            clear_fifo_send();
            clear_fifo_rec();
            UpdataBmuBootTimeSpan(i, true);
            DevBootData[i].OutTime = 0;
            DevBootData[i].Ack = 0;
            DevBootData[i].State = MyDefine.BootState_E.BS_SILENT;
            input_log.Clear();
        }
        private void btStartBoot_bmu1_Click(object sender, EventArgs e)
        {
            if(checkbootstatefun() == false)
            {
                return;
            }
            DevAddr = 0;
            DevBootDataStartInit(DevAddr);
        }

        private void btStartBoot_bmu2_Click(object sender, EventArgs e)
        {
            if (checkbootstatefun() == false)
            {
                return;
            }
            DevAddr = 1; 
            DevBootDataStartInit(DevAddr);
        }

        private void btStartBoot_bmu3_Click(object sender, EventArgs e)
        {
            if (checkbootstatefun() == false)
            {
                return;
            }
            DevAddr = 2; 
            DevBootDataStartInit(DevAddr);
        }

        private void btStartBoot_bmu4_Click(object sender, EventArgs e)
        {
            if (checkbootstatefun() == false)
            {
                return;
            }
            DevAddr = 3; 
            DevBootDataStartInit(DevAddr);
        }

        private void btStartBoot_bmu5_Click(object sender, EventArgs e)
        {
            if (checkbootstatefun() == false)
            {
                return;
            }
            DevAddr = 4; 
            DevBootDataStartInit(DevAddr);
        }

        private void btStartBoot_bmu6_Click(object sender, EventArgs e)
        {
            if (checkbootstatefun() == false)
            {
                return;
            }
            DevAddr = 5; 
            DevBootDataStartInit(DevAddr);
        }
        private void btStartBoot_bmu7_Click(object sender, EventArgs e)
        {
            if (checkbootstatefun() == false)
            {
                return;
            }
            DevAddr = 6;
            DevBootDataStartInit(DevAddr);
        }
        private void btStartBoot_bmu8_Click(object sender, EventArgs e)
        {
            if (checkbootstatefun() == false)
            {
                return;
            }
            DevAddr = 7;
            DevBootDataStartInit(DevAddr);
        }
        private void button32_Click_1(object sender, EventArgs e)
        {
            if (bmuSingleBoot|| bmuAutoBoot)
                return;
            bmuSingleBoot = true;
            SingleBootCnt = 0;
            SingleBootErrorCnt = 0;
        }
        bool bmuAutoBoot = false;
        void AutoTest1to8()
        {
            if (bmuAutoBoot)
            {
                if (++DevAddr > 7)
                {
                    bmuAutoBoot = false;
                }
            }
        }
        private void button31_Click(object sender, EventArgs e)
        {
            if (bmuAutoBoot|| bmuSingleBoot)
                return;
            DevAddr = 0;
            bmuAutoBoot = true;
            for (byte i = 0; i < 8; i++)
            {
                DevBootData[i].State = MyDefine.BootState_E.BS_NULL;
                DevBootData[i].progress = 0;
                setBMUprogressValue(i);
            }
        }

        private void label24_Click(object sender, EventArgs e)
        {
            for (byte i = 0; i < 8; i++)
            {
                if (DevBootData[i].State >= MyDefine.BootState_E.BS_SILENT)
                    return;
            }
            var label = sender as AntdUI.Label;
            var text = label.Text;
            string[] strs = text.Split('r');
            DevAddr = (byte)(Convert.ToByte( strs[1])-1);
            label32.Text = "BMU" + strs[1] + "循环测试:";
        }

        private void button36_Click(object sender, EventArgs e)
        {
            if (checkbootstatefun() == false)
            {
                return;
            }
            DevAddr = 8;
            DevBootDataStartInit(DevAddr);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            input6.Clear();
        }

        private void button37_Click(object sender, EventArgs e)
        {
            uint crc32temp = 0;
            byte[] DataBuffer = new byte[512];
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "二进制文件(*.bin)|*.bin";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                timer_boot.Enabled = true;
                input5.Text = fd.FileName;
                if (File.Exists(input5.Text) == false)
                {
                    input6.AppendText("\r\nBin文件加载失败\r\n");
                    return;
                }
                bmuInSilentMode();
                uint temp = (uint)new FileInfo(input5.Text).Length;
                BcuBootLogAppText("固件加载成功,固件大小:" + temp.ToString() + "byte\r\n", false);
                BinaryReader br = new BinaryReader(new FileStream(input5.Text, FileMode.Open));
                for (UInt32 AddrOffset = 0; AddrOffset < temp;)
                {
                    UInt16 read_data_num = (UInt16)br.Read(DataBuffer, 0, 512);
                    crc32temp = LibCal_Crc32Multi(DataBuffer, read_data_num, crc32temp, CRC32_FACTOR);
                    AddrOffset += read_data_num;
                }
                br.Close();
                
                DevBootData[8].FirmwareSize = temp;
                DevBootData[8].CrcSize = crc32temp;
                DevBootData[8].FirmwareVersion = 100;
                DevBootData[8].State = MyDefine.BootState_E.BS_NULL;
                DevBootData[8].progress = 0;
                setBMUprogressValue(8);
                DevBootData[8].CmdID = (uint)DBC_ID.BCUBOOTCMDID;
                DevBootData[8].DataID = (uint)DBC_ID.BCUBOOTDATAID;
                button36.Enabled = true;
            }
            else
            {
                button36.Enabled = false;
                BcuBootLogAppText("\r\n固件加载失败\r\n", false);
            }
        }

        /// <summary>
        /// 取消固件升级
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button30_Click_1(object sender, EventArgs e)
        {
            for (byte i = 0; i < 8; i++)
            {
                if(DevBootData[i].State > MyDefine.BootState_E.BS_NULL)
                    DevBootData[i].State = MyDefine.BootState_E.BS_FAIL;
            }
            bmuAutoBoot = false;
            bmuSingleBoot = false;
            BmuBootLogAppText("\r\n取消升级\r\n", false);
        }

        /// <summary>
        /// 将json格式的标定阈值写入文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="objList"></param>
        public void WriteJSONListToJsonFile(string filePath, IList<FaultJsonResult_class> jSONist)
        {
            string ListJson = "{\n\"FaultClbItem\":";
            ListJson += JsonConvert.SerializeObject(jSONist, Formatting.Indented);//
            ListJson += "\n}";
            File.WriteAllText(filePath, ListJson, Encoding.GetEncoding("GB2312"));
        }

        /// <summary>
        /// 切换到故障信息界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label6_Click(object sender, EventArgs e)
        {
            if(syshasfalutmessage && tabControl11.SelectedIndex != 3)
            {
                tabControl11.SelectedIndex = 3;
            }
        }

        
        int GetFacCrc32Val(clb_facinfo_t dst_p)
        {
            byte[] DataBuffer = new byte[10];
            DataBuffer[0] = (byte)dst_p.ClusterCellNum;
            DataBuffer[1] = (byte)dst_p.AfeCellNum;
            DataBuffer[2] = (byte)dst_p.PackNum;
            DataBuffer[3] = (byte)dst_p.BMUCellNum;
            DataBuffer[4] = (byte)dst_p.BMUAfeNum;
            DataBuffer[5] = (byte)dst_p.SWVersion;
            DataBuffer[6] = (byte)dst_p.HWVersion;
            DataBuffer[7] = (byte)dst_p.SNNum;
            DataBuffer[8] = (byte)dst_p.Test6;
            DataBuffer[9] = (byte)dst_p.Test7;
            uint CRC32 = LibCal_Crc32Multi(DataBuffer, 10, 0x5648, CRC32_FACTOR);
            return (int)CRC32;
        }
        /// <summary>
        /// 发送出厂设置命令和出厂信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button26_Click(object sender, EventArgs e)
        {
            //写出厂信息
            FactoryInfo.ClusterCellNum = Convert.ToUInt16(textBox99.Text);
            FactoryInfo.AfeCellNum = Convert.ToUInt16(textBox100.Text);
            FactoryInfo.PackNum = Convert.ToUInt16(textBox101.Text);
            FactoryInfo.BMUCellNum = Convert.ToUInt16(textBox102.Text);
            FactoryInfo.BMUAfeNum = Convert.ToUInt16(textBox103.Text);
            FactoryInfo.SWVersion = Convert.ToUInt16(textBox104.Text);
            FactoryInfo.HWVersion = Convert.ToUInt16(textBox105.Text);
            FactoryInfo.SNNum = Convert.ToUInt16(textBox106.Text);
            FactoryInfo.Test6 = Convert.ToUInt16(textBox107.Text);
            FactoryInfo.Test7 = Convert.ToUInt16(textBox108.Text);
            if(FactoryInfo.ClusterCellNum == 0|| FactoryInfo.AfeCellNum == 0|| FactoryInfo.BMUCellNum == 0|| FactoryInfo.PackNum == 0|| FactoryInfo.BMUAfeNum == 0)
                return;
            string strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_CLUSTERCELLNUM, Convert.ToInt32(textBox99.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_AFECELLNUM, Convert.ToInt32(textBox100.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_PACKNUM, Convert.ToInt32(textBox101.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_BMUCellNum, Convert.ToInt32(textBox102.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            
            strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_BMUAfeNum, Convert.ToInt32(textBox103.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_SWVersion, Convert.ToInt32(textBox104.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_HWVersion, Convert.ToInt32(textBox105.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_SNNum, Convert.ToInt32(textBox106.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_TEST6, Convert.ToInt32(textBox107.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_TEST7, Convert.ToInt32(textBox108.Text));
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
            
            //握手验证crc
            int CRC32 = GetFacCrc32Val(FactoryInfo);
             strText = Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_FACTORY, (UInt16)CLB_SIGNALNUM.CLB_W_FACINFO_CRC32, CRC32);
            my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
        }

        void adddatatochart()
        {
            double yValue = 50.0, xValue = 10;
            Random random = new Random();
            for (int pointIndex = 0; pointIndex < 100; pointIndex++)
            {
                yValue = yValue + (random.NextDouble() * 10.0 - 5.0);
                xValue = xValue + (random.NextDouble() * 5.0 - 2.0);
            }
        }
        

        private void toolStripMenuItemall_Click(object sender, EventArgs e)
        {
            if (MouseLocation == 1)
            {
                string str = Interaction.InputBox("过滤区间用 \"-\" 分隔", "设置CanID过滤范围", "0-3000", -1, -1);

                if (str.Contains("-"))
                {
                    string[] strarray = str.Split('-');
                    try
                    {
                        CanIDfiltrationMIN = Convert.ToInt32(strarray[0]);
                        CanIDfiltrationMAX = Convert.ToInt32(strarray[1]);
                    }
                    catch
                    {
                        CanIDfiltrationMIN = 0;
                        CanIDfiltrationMAX = 3000;
                    }                
                }
                else
                {
                    CanIDfiltrationMIN = 0;
                    CanIDfiltrationMAX = 3000;
                }
            }  
        }
        
    }
}